This project demonstrates how to use Docker Compose to containerize a simple Express.js server connected to a MongoDB database. It was built as a hands-on exercise to practice Docker Compose and container orchestration concepts.
docker-compose-project
│ ├── node_modules/ # Installed Node.js dependencies ├── Dockerfile # Docker image instructions ├── README.md # Project documentation ├── docker-compose.yaml # Compose file to manage multi-container setup ├── package-lock.json # Lock file for npm dependencies ├── package.json # Node.js project metadata and dependencies ├── server.js # Main Express server └── user.js # User schema and routes
- Node.js
- Express.js
- MongoDB
- Mongoose
- Docker
- Docker Compose
- Initialize Node.js project:
npm init -y - Install dependencies:
npm install express mongoose dotenv cors nodemon - Create
server.jswith a basic Express server. - Create
user.jsto define user schema and connect it to the server.
FROM node:20-alpineWORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD ["npm", "start"]
services: mongo: image: mongo:latest container_name: mongo_container ports: - "27017:27017" volumes: - mongo_data:/data/dbserver: build: . container_name: server_container ports: - "5000:5000" volumes: - .:/app - /app/node_modules depends_on: - mongo environment: - MONGO_URI=mongodb://mongo:27017/userDB
volumes: mongo_data:
- Build the Docker image manually (optional):
docker build -t compose-app . - Run the container manually (optional):
docker run --name compose-application -p 5000:5000 -v /app/node_modules -v ${PWD}:/app compose-app
This warning refers to a common issue when trying to connect a Docker container (like your Express.js app) to a MongoDB instance running outside of Docker, such as on your host machine.When you run your Express.js app inside a Docker container, it operates in an isolated environment with its own network stack. If MongoDB is running on your host machine, the container might not be able to resolve localhost or 127.0.0.1 to the host's MongoDB service.
Inside the container, localhost refers to the container itself — not your host machine. So, if your app tries to connect to mongodb://localhost:27017, it will look for MongoDB inside the container, where it doesn’t exist.Docker Compose allows you to define and run multi-container applications. In your case:
You define two services: mongo and server. Docker Compose creates a shared network for these services. The server container can access the mongo container using the service name mongo as the hostname.
So, in your docker-compose.yml, you correctly used:
environment: - MONGO_URI=mongodb://mongo:27017/userDB
- Start with Docker Compose:
docker compose upThis will spin up two containers:
mongo_containerfor MongoDBserver_containerfor the Express.js app
Using Docker Compose solves the issue of MongoDB and the server running in separate environments. By containerizing both, they can communicate seamlessly within the same network.