My first project with Node.js - an asynchronous event-driven JavaScript runtime, designed to build scalable network applications - was building an online trading platform in 2013. Since then, Node.js is one of my favorite technologies. I will show you how to dockerize your Node.js application based on Express - a fast, unopinionated, minimalist web framework - and run it on AWS Fargate in this blog bost. I like AWS Fargate because running containers in the cloud were never easier.

This blog post is an excerpt from our book Rapid Docker on AWS.

Read on to learn how to build a Docker image for a Node.js application.

Building the Docker image

The Dockerfile is based on the official Node.js Docker Image: node:10.16.2-stretch . Static files (folders img and css ) are served by Express as well as the dynamic parts. The following details are required to understand the Dockerfile :

envsubst is used to generate the config file from environment variables

is used to generate the config file from environment variables npm ci --only=production installs the dependencies declared in package.json ( package-lock.json , to be more precise)

installs the dependencies declared in ( , to be more precise) The Express application listens on port 8080

The Express application’s entry point is server.js and can be started with node server.js

A simple server.js file follows. Yours likely is more complicated.

server.js const express = require ( 'express' );



const app = express();

app.use( '/css' , express.static( 'css' ));

app.use( '/img' , express.static( 'img' ));



app.get( '/health-check' , (req, res, next) => {

res.sendStatus( 200 );

});



app.listen( 8080 , '0.0.0.0' );



Customization Most likely, your folder structure is different. Therefore, adapt the Copy config files and Copy Node.js files section in the following Dockerfile to your needs.

docker/Dockerfile FROM node: 10.16 . 2 -stretch



WORKDIR /usr/src/app



ENV NODE_ENV production





RUN apt-get update && apt-get install -y gettext

COPY docker/custom-entrypoint /usr/ local /bin/

RUN chmod u+x /usr/ local /bin/custom-entrypoint

ENTRYPOINT [ "custom-entrypoint" ]

RUN mkdir /usr/src/app/config/





COPY config/*.tmp /tmp/config/





COPY package*.json /usr/src/app/

RUN npm ci --only=production





COPY css /usr/src/app/css

COPY img /usr/src/app/img

COPY views /usr/src/app/views

COPY server.js /usr/src/app/





EXPOSE 8080

CMD [ "node" , "server.js" ]



The custom entrypoint is used to generate the config file from environment variables with envsubst .

docker/custom-entrypoint

set -e



echo "generating configuration files"

FILES=/tmp/config/*

for f in $FILES

do

c=$(basename $f .tmp)

echo "... $c "

envsubst < $f > /usr/src/app/config/ ${c}

done



echo "starting $@ "

exec " $@ "



Next, you will learn how to test your containers and application locally.

Testing locally