Using Docker for local Node.js development

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.

Image for post
Image for post

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 Nodejs 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.

Prerequisites:

Creating 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

2. Edit src/index.js .

3. Add script to package.json.

"srcipts": {
"dev": "nodemon src/index.js"
...
}

Configuring Dockerfile and docker-compose.yml

  1. Add Dockerfile.

2. Add docker-compose.yml .

3. Add script to package.json .

"scripts": {
"docker:dev": "docker-compose up"
...
}

Running all together

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

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

2. You can check “http://localhost:3000”.

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

Conclusion

All source code available on Github.

Sr. Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store