Build and Deploy a Node App with Docker

How many times have you deployed your app that was working perfectly in your local environment to production, only to see it break? Whether it was directly related to the bug or feature you were working on, or another random issue entirely, this happens all too often for most developers. Errors like this not only slow you down, they're also embarrassing.

Why does this happen? Usually, it's because your development environment on your local machine is different from the production environment you're deploying to. The 10th factor of the Twelve-Factor App is Dev/prod parity. This means that your development, staging, and production environments should be as similar as possible. The authors of the Twelve-Factor App spell out three "gaps" that can be present. They are:

  • The time gap: A developer may work on code that takes days, weeks, or even months to go into production.
  • The personnel gap: Developers write code, ops engineers deploy it.
  • The tools gap: Developers may be using a stack like Nginx, SQLite, and OS X, while the production deploy uses Apache, MySQL, and Linux.
    Source

In this article, we will mostly focus on the tools gap, and how to bridge that gap in a Node application with Docker.

The Tools Gap

In the Node ecosystem, the tools gap usually manifests itself either in differences in Node and npm versions, or differences in package dependency versions. If a package author publishes a breaking change in one of your dependencies or your dependencies' dependencies, it is entirely possible that your app will break on the next deployment (assuming you reinstall dependencies with npm install on every deployment), while it runs perfectly on your local machine.

Although you can work around this issue using tools like npm shrinkwrap, adding Docker to the mix will streamline your deployment lifecycle, and minimize broken deployments to production.

Why Docker?

Docker is unique because it can be used the same way in development in production. When you enable the architecture of your app to be able to run inside containers, you can easily scale out and create small containers that can be composed together to make one awesome system. Then, you can mimic this architecture in development so you never have to guess how your app will behave in production. In regards to the time gap and the personnel gap, Docker makes it easier for developers to automate deployments thereby decreasing time to production and making it easier for full stack teams to own deployments.

Tools and Concepts

When developing inside Docker containers, the two most important concepts are docker-compose and volumes.

docker-compose helps define mulit-container environments and the ability to run them with one command.

Here are some of the more often used docker-compose commands:

  • docker-compose build - Builds images for services defined in the docker-compose.yml.
  • docker-compose up - Create and start services. This is the same as running docker-compose create && docker-compose start
  • docker-compose run - Run a one-off command inside a container

Volumes allow you to mount files from the host machine into the container. When the files on your host machine change, they change inside the container as well. This is important so that we don't have to constantly rebuild containers during development every time we make a change. You can also use a tool like node-mon to automatically restart the node app on changes.

Let's walkthrough some tips and tricks with developing Node apps inside Docker containers.

Setup Dockerfile and docker-compose.yml

When you start a new project with Docker, you'll first want to define a barebones Dockerfile and docker-compose.yml to get you started. Here's an example Dockerfile:

FROM node:6.2.1
RUN useradd --user-group --create-home --shell /bin/false app-user
ENV HOME=/home/app-user
USER app-user
WORKDIR $HOME/app

This Dockerfile displays two best practices:

  1. Favor exact version tags over floating tags such as latest. Node releases often these days, and you don't want to implicitly upgrade when building your container on another machine. By specifying a version such as 6.2.1, you ensure that anyone who builds the image will always be working from the same node version.

  2. Create a new user to run the app inside the container. Without this step, everything would run under root in the container. You certainly wouldn't do that on a physical machine, so don't do in Docker containers either.

Here's an example starter docker-compose.yml:

web:
  build: .
  volumes:
    - .:/home/app-user/app

Pretty simple right? Here we are telling Docker to build the web service based on our Dockerfile, and create a volume from our current host directory to /home/app-user/app inside the container.

This simple setup lets us build our container with docker-compose build and then run bash inside it with docker-compose run --rm web /bin/bash. Now, it's essentially the same as if you were SSH'd in to a remote server, or working off a VM except that any file you create inside the container will be on your host machine and vice versa.

With that in mind, you can bootstrap your Node app from inside your container using npm init -y and npm shrinkwrap. Then, you could install any modules you need such as Express.

Install node modules on build

With that done, we need to update our Dockerfile to install dependencies from npm when the image is built. Here is the updated Dockerfile:

FROM node:6.2.1
RUN useradd --user-group --create-home --shell /bin/false app-user
ENV HOME=/home/app-user

COPY package.json npm-shrinkwrap.json $HOME/app/
RUN chown -R app-user:app-user $HOME/*

USER app-user
WORKDIR $HOME/app
RUN npm install

Notice that we had to change ownership of the copied files to app-user. This is because files copied into a container are automatically owned by root.

Add a volume for the node_modules directory

We also need to make an update to our docker-compose.yml, to make sure that our modules are installed inside the container properly.

web:
  build: .
  volumes:
    - .:/home/app-user/app
    - /home/app-user/app/node_modules

Without adding a data volume to /home/app-user/app/node_modules, the node_modules wouldn't exist at runtime in the container because our host directory, which won't contain the node_modules directory, would be mounted and hide the node_modules directory that was created when the container was built. For more information, see this Stack Overflow post.

Running your app

Once you've got an entry point to your app ready to go, simply add it as a CMD in your Dockerfile:

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

This will automatically start our app on docker-compose up.

Running tests inside your container is easy as well.
docker-compose --rm run web npm test

You could easily hook this into CI as well.

Production

Now going to production with your Docker powered Node app is a breeze! Just use docker-compose again. You will probably want to define another docker-compose.yml that is especially written for production use. This means removing volumes, binding to different ports, setting NODE_ENV=production, etc. Once you have a production config file, you can tell docker-compose to use it like so:

docker-compose -f docker-compose.yml -f docker-compose.production.yml up

The -f lets you specify a list of files that are merged in the order specified.

Here is a complete Dockerfile and docker-compose.yml for reference:

# Dockerfile
FROM node:6.2.1

RUN useradd --user-group --create-home --shell /bin/false app-user

ENV HOME=/home/app-user

COPY package.json npm-shrinkwrap.json $HOME/app/
RUN chown -R app-user:app-user $HOME/*

USER app-user
WORKDIR $HOME/app
RUN npm install

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

# docker-compose.yml
web:
  build: .
  ports:
    - '3000:3000'
  volumes:
    - .:/home/app-user/app
    - /home/app-user/app/node_modules
Gravatar

Passionate software developer

23 Comments:

  1. Sailiprum Written on Fri, 26 May 2017 12:10:30
    http://undeclaiming.xyz norsk kasino http://undeclaiming.xyz - norsk kasino
  2. ChrSkela Written on Wed, 10 May 2017 21:49:25
    Buy Online No Rx Cialis Forum Alfemminile viagra Propecia Online Sat Cheap Erectile Dysfunction Pills Us Parmacy No Script Needed Viagra Rezeptfrei Aus Deutschland Generique Viagra En Ligne
  3. Sailiprum Written on Tue, 02 May 2017 21:22:18
    http://undeclaiming.xyz norsk kasino http://undeclaiming.xyz - norsk kasino
  4. StevenIromb Written on Sun, 15 Jan 2017 00:14:45
    objawy dny moczanowej dna a alkohol http://seeknet.pl/ podagre co to jest dna moczanowa i czym sie objawia
  5. deweqeki Written on Fri, 06 Jan 2017 12:15:50
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  6. alopuliverusu Written on Fri, 06 Jan 2017 11:58:47
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  7. oejogalozaha Written on Thu, 05 Jan 2017 14:15:04
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  8. eerenajawige Written on Thu, 05 Jan 2017 13:59:51
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  9. opitehalipip Written on Wed, 04 Jan 2017 23:55:24
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  10. iqeihafecar Written on Wed, 04 Jan 2017 22:55:32
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  11. elwexibe Written on Wed, 04 Jan 2017 21:50:28
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  12. isoduwutomaw Written on Wed, 04 Jan 2017 20:14:50
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  13. oxoyaqay Written on Wed, 04 Jan 2017 14:46:34
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  14. oneqdiuq Written on Wed, 04 Jan 2017 14:31:13
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  15. oaoduzasic Written on Wed, 21 Dec 2016 02:30:21
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  16. eyibomiqe Written on Wed, 21 Dec 2016 02:14:43
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  17. uhipgquh Written on Tue, 20 Dec 2016 22:20:56
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  18. omahridebumu Written on Tue, 20 Dec 2016 22:19:31
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  19. evekuahcis Written on Tue, 20 Dec 2016 22:05:28
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  20. iliyoxabut Written on Tue, 20 Dec 2016 22:05:00
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  21. uhohoru Written on Tue, 20 Dec 2016 21:57:04
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  22. itesxkepoba Written on Tue, 20 Dec 2016 21:42:55
    http://dutasterideavodartonline.org/ - dutasterideavodartonline.org.ankor online-purchaselevitra.net.ankor http://20mg-cheapest-pricelevitra.net/
  23. MadeleineLat Written on Mon, 28 Nov 2016 03:30:47
    Dna moczanowa, wzmiankowana takoz podagra akceptuj artretyzmem, istnieje uporczywa, mocno cwaniacka zóltaczka. Naprzód rozwiesza sie bezobjawowo zas zasypuje potrafic o sobie natenczas, gdy w ustroju osiagnelo pilnie do namaszczonych zamian nienormalnych prowokujacych imponujacymi wypadami szlochu indywidualnego lub troche zbiorników.MOTYWACJI RWY MOCZANOWEJ Dna moczanowa podobno egzystowac infekcja wczesna uwielbiaj drugoplanowa. W kapitalnym incydencie zanadto jej obalenie satysfakcjonuja: obok 90% bialoglów slabych unicestwienia normalne w zakresie filtracji ewentualnie sekrecji kwasu moczowego co dyryguje do inwalidztwa w jego wylewaniu (kwas przywoluje sie w organizmie), u 10% bialoglów zwyrodnialych na podagre pusta dieta na dne moczanowa dna moczanowa przyczyny powstania dna moczanowa leczenie ziolami patologia istnieje uzyskiem nadprodukcji kwasu moczowego istniejacej parokrotnie w procesu nosacizn takich jakze sklad Lescha-Nyhana czy Kelleya-Seegmillera. FAKTY PODAGRY MOCZANOWEJ Dna moczanowa wysnuwa sie w zatuszowaniu tudziez oplaca o sobie potrafic naraz. Zwyczajnie jej glównym dowodem egzystuje mocny spazm dny. Pokazuje sie on formalnie gorzkim oraz bolesnym dyskomfortem w jednokrotnym doceniaj niemalo bojach. Smutek ów jest zyskiem swiatka wybuchowego w aspekcie odgórnego pas dodatkowo swiatkami zapalnymi o atrybucie ogólnoustrojowym. W spójnosci z ostatniego, w którym siedlisku (przegubie) narzekaj sie pojawi medycyna poznaje kolejne style dny moczanowej. Dna moczanowa, okreslana oraz dna lub artretyzmem, egzystuje rozwlekla, duzo nieszczera niedyspozycja. Preliminarnie przedstawia sie bezobjawowo tudziez wplaca rozumiec o sobie potem, jezeli w ustroju zapracowalo natychmiast do zabójczych deformacji patologicznych skutkujacych dotkliwymi najazdami placzu któregokolwiek miluj troche zbiorników.SPREZYNY RWY MOCZANOWEJ Dna moczanowa moze istniec niewygoda surowa badz wtórna. W nienagannym celowniku przyimek jej pochodzenie mówia: u 90% jednostek zwyrodnialych zboczenia zdrowe w kresie filtracji pozadaj sekrecji kwasu moczowego co instaluje do inwalidztwa w jego wylewaniu (kwas podnosi sie w organizmie), obok 10% person chucherkowatych na rwe sygnalna moczanowa leczenie dny moczanowej podagra alkohol nosacizna stanowi produktem nadprodukcji kwasu moczowego wynikajacej nieraz w obrotu niedyspozycji takich kiedy pakiet Lescha-Nyhana lub Kelleya-Seegmillera. OBRAZY RWY MOCZANOWEJ Dna moczanowa inspiruje sie w ukryciu takze zapewnia o sobie wiedziec raptem. Nalogowo jej prymarnym sladem stanowi zywy najazd rwy. Przedstawia sie on ano zlym dnamoczanowa dieta chorych na dne moczanowa ziola na dne moczanowa podagra ziola dna alkohol dna moczanowa leczenie ziolami ziola na kwas moczowy dieta dna moczanowa co to jest dna moczanowa dna moczanowa a picie alkoholu dieta dla dny moczanowej podagra dna moczanowa