← Go back

Using Docker for local Node.js development

· 1 min read

This article shows how to create a simple Node.js app and setup Docker for running the app locally in watch mode inside a container.

Docker + Node.js = <3

Why use Docker for development?

  • Easy starting. New developers need only Docker CE as a prerequisite.
  • The same environment. Everyone working on the project will have the exact same environment (including Node.js and npm versions, as well as node_modules, if using package-lock.json or yarn.lock). Also min diff with production environment, if app runs in docker container on prod.


Getting Started

Create a Node.js app

  1. Create a new project.
  # Create new app directory
  npm i my-app
  # Initialize with
  npm init -y
  # Install express
  npm i express --save
  # Install nodemon for running an app in watch mode
  npm i nodemon --save-dev
  #create src dir and file inside
  mkdir src && touch src/index.js
  1. Edit src/index.js.
const express = require("express")
const PORT = process.env.PORT || 3000
const app = express()

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

app.listen(PORT, () => console.log(`App listening on port ${PORT}!`))
  1. Add script to package.json.
  "srcipts": {
    "dev": "nodemon src/index.js"

Configure Dockerfile and docker-compose.yml

  1. Add Dockerfile.
  # Use small base image with nodejs 10
  FROM node:10.13-alpine

  # set current work dir
  WORKDIR /usr/src/app

  # Copy package.json, packge-lock.json into current dir
  COPY ["package.json", "package-lock.json*", "./"]

  # install dependencies
  RUN npm i

  # copy sources
  COPY . .

  # open default port
  EXPOSE 3000

  # Run app
  CMD ["node", "start"]
  1. Add docker-compose.yml.
version: "3"

    image: my-app
    build: .
      NODE_ENV: development
      - 3000:3000
    command: npm run dev
      # mount current dir into docker container
      - .:/my-app
      # ignore local node_modules, use container
      - /my-app/node_modules
  1. Add script to package.json.
  "scripts": {
    "docker:dev": "docker-compose up"

Run an app

  1. Run application in docker container in watch mode: npm run docker:dev.

This will build a container using Dockerfile, mount local directory into the container’s app directory and start an app in watch mode.

  1. You can check http://localhost:3000.

You can change your source files, nodemon will restart as usual on file changes.


All source code is available on Github.

© 2024 Erzhan Torokulov