Using Docker to Run Nodejs Apps

Docker is one of the most popular deployment tools available today for application developers. There are many books and tutorials about Docker out there, but docker is basically a tool to package your app as an image and run it in isolation as a container.

In a micro/multy service environment you want to make sure that your service will run no matter what. One of the obstacles is Nodejs version and environment variables. when running multiple services on a single machine / environment, collisions are bound to happen. Docker addreses this issue by providing each service with it’s own isolated container that is not affected by other processes.

A simple but effective technique is to run a Nodejs container and simply mount a volume with your code and have it execute. From within the project dir run:

docker run --rm -it -v $(pwd):/src -w /src node:0.12.7 npm install

Lets break this down:

docker run : will run a docker container

–rm : tells docker to remove the container if it exists

-it : Keep STDIN open even if not attached + Allocate a pseudo-TTY

-v $(pwd):/src : mount the current directory ($(pwd)) to /src on the docker container. This is faster than copying files to the image (the process that we ma want to do when preparing for production)

node:0.12.7 : Pull and run an image with node version 0.12.7 on it

npm : the command to run on the container

install : the parameter for the npm command

Now that npm has installed all the dependencies you can run:

docker run --rm -it -v $(pwd):/src -w /src node:0.12.7 node index.js

or if you have a start script in your ‘package.json’:

docker run --rm -it -v $(pwd):/src -w /src node:0.12.7 npm start

This will mount the volume again and start the app

You can also set environment variables through the docker run command. for more options checkout the docs

Javascript Architect

Frontend Group