Dockerizing a Node.js App

In this tutorial, I’ll quickly show you how to Dockerize a Nodejs app. I want cover what docker is or why – hopefully that’s why you found this post. Let’s get to it.

Creating the Project

Start by creating a new project

mkdir nodejs-docker
cd nodejs-docker/
npm init -y
touch index.js
touch Dockerfile

The only thing new above should be the Dockerfile. This is where we will declare the commands for docker to run.

And here is the docker file with coments on the steps.

FROM node:8 # Tell Docker to start from a Node:8 image (this is maintained by node)

WORKDIR /home/user/nodejs-docker # Add the absolute path to our project directory

COPY . . # Copy all of the current directory (the one above) to the Docker directory

RUN npm install --production # Install everything we need from production

CMD ["node", "index.js"] # Run the app!

Building and Running

Now that we have the project set up, let’s build and run the app.

Here is the build command. This builds our current directory (find that Dockerfile) and creates and image.

docker build -t nodejs-docker .

We can view images on our machine with this.

docker image ls

Finally, to run the command we do the following command:

docker run -p 8080:80 nodejs-docker

This command runs our docker image and forward the outside port 8080 to port 80 in the docker container. To get this to work, you will need to build something like an Express app to listen to port 80.

And, that’s about it! If you like to explore further, I recommend checking out this blog: https://nodesource.com/blog/containerizing-node-js-applications-with-docker and the official docs: https://docs.docker.com/get-started/