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.
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 usingpackage-lock.json
oryarn.lock
). Also min diff with production environment, if app runs in docker container on prod.
Prerequisites:
- Docker CE (community edition). You can find and install from the Docker official website.
Getting Started
Create a Node.js app
- 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
- 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}!`))
- Add script to package.json.
"srcipts": {
"dev": "nodemon src/index.js"
...
}
Configure Dockerfile and docker-compose.yml
- 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"]
- Add docker-compose.yml.
version: "3"
services:
my-app:
image: my-app
build: .
environment:
NODE_ENV: development
ports:
- 3000:3000
command: npm run dev
volumes:
# mount current dir into docker container
- .:/my-app
# ignore local node_modules, use container
- /my-app/node_modules
- Add script to package.json.
"scripts": {
"docker:dev": "docker-compose up"
...
}
Run an app
- 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.
- You can check http://localhost:3000.
You can change your source files, nodemon will restart as usual on file changes.
Conclusion
All source code is available on Github.