Node.js Webapp In a Docker Image – MEAN


Node js applications are great for proof of concepts and getting apps made in a short amount of time. Running them inside a docker container is a great security blanket and lets applications be versioned much like software version control. This is a quick code snippet of a nodejs server using express. This is then packaged into a docker image that can be deployed to any machine running docker.



[enlighter language=”json”]
“name”: “apiTest”,
“version”: “1.0.0”,
“description”: “API for”,
“main”: “server.js”,
“private”: “true”,
“scripts”: {
“start”: “node server.js”
“author”: “Derek Carr”,
“license”: “MIT”,
“url”: “”,
“dependencies”: {
“body-parser”: “*”,
“express”: “^4.13.3”,

Express JS


var express = require('express');
var bodyParser = require('body-parser');

// Server Vars
var app = express();
var port = process.env.PORT || 9800;

//Configuration of App
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
app.set('trust proxy'); // trust first proxy

app.get("/test", function (req, res, next) {

app.listen(port, function () {
console.log("Server started @ " + port);

module.exports = app;


One of the benefits of Docker Images is the layers we can make. Most tutorials on the internet show that you need to pull down an ubuntu or centos image, install node, and do all sorts of updates to the machine in order to run npm apps. Google has a repo in where they took the time to build a base image and strip it down to the bare essentials to run node apps. This makes your total image size smaller and all you have to do as a developer is make sure your package.json has the right dependencies.


FROM google/nodejs-runtime

MAINTAINER Derek Carr <>

ADD package.json /app/
RUN npm install
ADD . /app


CMD []
ENTRYPOINT ["/nodejs/bin/npm", "start"]

Building The Image

This lets

docker build -t $DOCKER_IMAGE:$TAG .
docker push $DOCKER_IMAGE:$TAG
#Clean up docker images
docker images | grep "$DOCKER_IMAGE" | awk '{print $3}' | xargs docker rmi


You need to have docker installed and the daemon running. You also need to be logged into docker – which can be done by running docker login from the command line.

Comments are closed.