How to run MongoDB container
Here’s a simple Docker Compose file to run a MongoDB container:
version: '3.8'
services:
mongo:
image: mongo:latest
container_name: mongodb
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Explanation:
- version: Specifies the Docker Compose file version.
- services: Defines the services to be run. Here, we have one service,
mongo
. - image: The Docker image for MongoDB.
- container_name: The name of the MongoDB container.
- ports: Maps port 27017 of the container to port 27017 on your host machine.
- environment: Sets environment variables for the MongoDB root username and password. You can change these values as needed.
- volumes: Mounts a named volume (
mongo_data
) to persist MongoDB data even if the container is removed.
Running the Container
To start the MongoDB container using this Docker Compose file:
- Save the above YAML configuration in a file named
docker-compose.yml
. - Open a terminal and navigate to the directory where the file is saved.
- Run the following command:
docker-compose up -d
This will start the MongoDB container in detached mode. You can then connect to MongoDB at localhost:27017
with the credentials specified in the environment variables.