Docker Node.js Express Server

Setting up a Node.js Express server to use within Docker is useful. Docker will be helpful to quickly mock up some api endpoints and keep environments simple.

In the next article we will go through what it will take to deploy this Docker container to Heroku with Gitlab.

Creating our working directory

Let’s create a directory we can work out of. In this directory we will have all our files to run a Node.js Express server, and a Docker container.

In the next article we will set up this directory to use version control with Gitlab.

Creating a Node.js Express server

Let’s start building our Express server. If you don’t know what Node.js or Express is then I suggest you research those technologies. This article assumes you know the basics of Javascript, Node.js, and Express.

Create the package.json file:

Running this command will ask you some questions about how to set up your Node package. Give it the name my-app and accept the default parameters.

Now we will install a npm package to help us set up the Express server. If you need more control over Express I suggest you use the Express package right out of the box.

Let’s create some run scripts we can use to start the server. Add this to your package.json file.

Create an index.js file:

When we run npm start it will start the server we defined in the index.jsfile. Using the package boilerpress it will help us quickly mock up a server.

Creating the Docker image

Create a file named Dockerfile:

This is the a simple Dockerfile. You will probably want to set a specific version of the node image to build from and set up a user, but this will work for a quick mock up.

This will copy over the entire working directory to inside the docker image at /usr/src/app.

Create a docker-compose.yml file:

Let’s set up an .env file that we can use to have environment variables inside our docker image.

Create a .env file:

Now we can run docker commands to build our image and run the container:

Testing the running server

Navigate with your browser to:

You will see the words Hello World!

In the next article we will build upon this example, set up some more api endpoints and go through what it will take to deploy this Docker server to Heroku with Gitlab.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store