Docker Compose for Node.js and MongoDB: Setup Guide
Use a
docker-compose.yml file to define services for node.js and mongodb. This file sets up MongoDB as a database service and Node.js as an app service that connects to it, making it easy to run both with one command.Syntax
A docker-compose.yml file defines multiple services that run together. Each service has a name and configuration like the image to use, ports to expose, environment variables, and volumes for data.
Key parts:
- version: Docker Compose file format version.
- services: List of containers to run.
- image: Docker image to use for the service.
- ports: Map container ports to host ports.
- environment: Set environment variables inside the container.
- volumes: Persist data or share files between host and container.
yaml
version: '3.8' services: service_name: image: image_name:tag ports: - "host_port:container_port" environment: - ENV_VAR=value volumes: - host_path:container_path
Example
This example shows a docker-compose.yml file that runs MongoDB and a Node.js app. MongoDB stores data, and Node.js connects to it using the service name mongodb as the database host.
yaml
version: '3.8' services: mongodb: image: mongo:6.0 restart: always ports: - "27017:27017" volumes: - mongo-data:/data/db nodeapp: build: ./nodeapp ports: - "3000:3000" environment: - MONGO_URL=mongodb://mongodb:27017/mydatabase depends_on: - mongodb volumes: mongo-data:
Output
Starting mongodb ... done
Starting nodeapp ... done
# Node.js app listens on port 3000 and connects to MongoDB at mongodb:27017
Common Pitfalls
- Wrong MongoDB host: Using
localhostinside Node.js container won't work; use the MongoDB service namemongodbinstead. - Missing depends_on: Node.js might start before MongoDB is ready; use
depends_onto start MongoDB first. - Data loss: Not using volumes for MongoDB causes data to be lost when container stops.
- Port conflicts: Make sure host ports (like 27017 or 3000) are free before running.
yaml
Wrong example:
services:
nodeapp:
environment:
- MONGO_URL=mongodb://localhost:27017/mydatabase
Right example:
services:
nodeapp:
environment:
- MONGO_URL=mongodb://mongodb:27017/mydatabase
depends_on:
- mongodbQuick Reference
Remember these tips when using Docker Compose with Node.js and MongoDB:
- Use service names as hostnames to connect containers.
- Use volumes to keep MongoDB data safe.
- Use
depends_onto control startup order. - Expose ports to access services from your machine.
Key Takeaways
Define Node.js and MongoDB as services in a single docker-compose.yml file.
Use the MongoDB service name as the database host inside Node.js environment variables.
Add volumes to MongoDB service to persist data across container restarts.
Use depends_on to ensure MongoDB starts before Node.js app.
Map ports to access Node.js app and MongoDB from your host machine.