Minimal Docker Compose File For Node Js Application Development

Ashok Raja T
Technology Specialist
June 30, 2019
Rate this article
Views    6350

In this article, let’s have a look into a no frills minimal docker compose file of a Node Js (express js) application for local development. Having a docker file as a part of the project might be a much easier solution in most scenarios. But, if you are looking for docker compose file with reference to pm2 for watching your code files, then the below code will help.

Docker Compose File (docker-compose.yml)

version: '3'

services:
  n12:
    image: node:12-alpine
    container_name: "node12"
    restart: unless-stopped
    ports:
      - 4000:3000
    volumes:
      - ./data/app:/home/node/app
    working_dir: /home/node/app
    command: >
      sh -c "npm install -g pm2 && npm install && pm2-runtime server.js --watch"

Key Points to consider

  1. If you look at the docker compose file, it’s very similar to docker file of a Node Js application. The only major difference is, you cannot use COPY command in docker compose. Instead, you can map your local folder to a docker volume.
  2. Working Directory can be specified in compose file similar to docker file but the syntax contains a “_” in between “working” and “directory” (working_directory).
  3. In a regular node application, app files are executed and watched by pm2 with command “pm2 start server.js --watch” but inside a container, the command is “pm2-runtime server.js --watch
  4. “alpine” image is used as the base image in this compose file. As “alpine” doesn’t have “bash” by default, “bin\sh” (shell) is been directly invoked.

server.js

The below is the code for a basic Express Js Server which is used to validate the container.

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

app.get('/', (req, res) => res.send('Hello From Docker !!!'));

app.listen(port, () => console.log(`Server listening on port ${port}!`));

OutPut

Mapped Folder
vs code docker compose

Output in browser
express js output

Subscribe To Our Newsletter
Loading

Leave a comment