How to Deploy Node.js Using Docker: Simple Guide
To deploy a
Node.js app using Docker, create a Dockerfile that sets up the Node environment and copies your app code. Then build a Docker image with docker build and run it as a container using docker run.Syntax
A typical Dockerfile for Node.js includes these parts:
- FROM: base image with Node.js installed
- WORKDIR: sets the working directory inside the container
- COPY: copies your app files into the container
- RUN: runs commands like installing dependencies
- EXPOSE: declares the port your app listens on
- CMD: command to start your Node.js app
dockerfile
FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "index.js"]
Example
This example shows a simple Node.js app deployed with Docker. It uses the official Node.js 18 image, installs dependencies, copies app files, exposes port 3000, and starts the app.
dockerfile
/* index.js */ const http = require('http'); const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello from Dockerized Node.js!'); }); server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); }); /* package.json */ { "name": "docker-node-app", "version": "1.0.0", "main": "index.js", "scripts": { "start": "node index.js" }, "dependencies": {} } /* Dockerfile */ FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "index.js"]
Output
Server running at http://localhost:3000/
Common Pitfalls
Common mistakes when deploying Node.js with Docker include:
- Not copying
package.jsonbefore runningnpm install, causing unnecessary reinstall on every build. - Forgetting to expose the port your app listens on, so Docker won't map it correctly.
- Using
CMDincorrectly, which can prevent the app from starting. - Not setting the working directory, leading to file path errors.
dockerfile
/* Wrong Dockerfile snippet */ FROM node:18 COPY . . RUN npm install CMD ["node", "index.js"] /* Right Dockerfile snippet */ FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "index.js"]
Quick Reference
Remember these key Docker commands for Node.js deployment:
docker build -t your-app-name .- builds the Docker image from your Dockerfiledocker run -p 3000:3000 your-app-name- runs the container and maps port 3000docker ps- lists running containersdocker logs container-id- shows logs from your container
Key Takeaways
Create a Dockerfile with Node.js base image, copy files, install dependencies, expose port, and start the app.
Build your Docker image using 'docker build' and run it with 'docker run' mapping the correct ports.
Always copy package.json before running npm install to optimize build caching.
Expose the port your Node.js app listens on to allow external access.
Use CMD with JSON array syntax to correctly start your Node.js app inside the container.