Deploying a Node.js project with Docker makes your development and production setup consistent and scalable. Here’s how I containerized a simple Node.js app and ran it locally using Docker and Docker Compose.
Step 1: Create a dockerfile
In your project root, create a .dockerfile
(you can also name it Dockerfile
without the dot prefix for convention):
FROM node:16-alpine
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
EXPOSE 3033
CMD [ "node", "index.js" ]
Step 2: Build the Docker Image
docker build -t devk3/mongotest .
This command packages your app into a Docker image tagged as devk3/mongotest.
Step 3: Run the Container Locally
docker run -p 2000:3033 devk3/mongotest
Now your Node.js app will be running on http://localhost:2000, forwarding traffic to the container’s port 3033.
Step 4: Push to Docker Hub
Make sure you’re logged in (docker login) and then push:
docker push devk3/mongotest:latest
Your image is now publicly available on Docker Hub and can be pulled from anywhere.
Step 5: Use Docker Compose for Simpler Setup
To simplify local development or multi-container setups, use Docker Compose. Create a docker-compose.yml file:
version: "3.8"
services:
web:
image: devk3/mongotest
ports:
- "2222:3033"
env_file:
- .env
Start it with: docker-compose up
Access your app at http://localhost:2222.
Using Docker and Docker Compose:
- Keeps development and production environments consistent
- Easily share and deploy your app anywhere
- Secure and scale with additional services (like MongoDB, Redis, etc.)
Github link:
https://github.com/khatridev/nodejs-mongo-docker-boilerplate