This quick tutorial shows you how to dockerize a Node.js Express Server.

Step 1: Create Node.js Express Server

Let’s create a simple Node.js Express Server to demonstrate the usage of each command. Skip this step if you already have a Node.js application for this exercise.

$ mkdir my-server && cd my-server/
$ npm init
...
...
$ npm install express
$ vi server.js

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`My server listening at http://localhost:${port}`))
$ vi package.json

{
  "name": "my-server",
  "version": "1.0.0",
  "description": "Node.js Express Server",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Step 2: Build Docker image

Create a Dockerfile.

$ vi Dockerfile

FROM node:10-alpine

RUN mkdir -p /src/app
WORKDIR /src/app

COPY package.json /src/app/package.json
RUN npm install
COPY . /src/app

EXPOSE 3000
CMD [ "npm", "start" ]

Based on your Dockerfile, start building the Docker image.

$ docker build -t app-image .
...
...

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
app-image           latest              33afc33f3aec        6 seconds ago       87.1MB
node                10-alpine           a07f309c9753        2 weeks ago         83.8MB

Step 3: Run Docker container

Run the application with below command (--rm: remove container on exit, -d: run container in detached mode, --name: specify a name for container, -p: specify exposed port mapping).

$ docker run --rm -d --name app-container -p 3000:3000 app-image
6549daadfd0a457c6230401e90c4263f21967ceee7041a2e9b37c861025e8e9d

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS        PORTS                    NAMES
6549daadfd0a        app-image           "docker-entrypoint.s…"   12 seconds ago      Up 11 seconds       0.0.0.0:3000->3000/tcp   app-container

$ curl localhost:3000
Hello World!

👉 Any questions? Please comment below.


Leave a comment