# Docker Compose file format version # 3.9 is a commonly used Compose file version # version: "3.9" # Defines all containers (services) that belong to this application services: # MongoDB database service mongo: # Uses the official MongoDB image, version 7 image: mongo:7 # Gives the container a fixed name so it is easier to identify in Docker container_name: mongo-crud-db # Automatically restarts the container if it stops because of a failure restart: on-failure # Environment variables passed into the MongoDB container environment: # Creates the MongoDB root/admin username on first startup MONGO_INITDB_ROOT_USERNAME: admin # Creates the MongoDB root/admin password on first startup MONGO_INITDB_ROOT_PASSWORD: admin123 # Connects this container to the custom Docker network below networks: - mongo-crud-net # Mounts a named Docker volume into MongoDB's data folder # This keeps database data persistent even if the container is recreated volumes: - mongo_crud_data:/data/db # Flask web application service web: # Builds the image from the Dockerfile in the current folder build: . # Gives the web container a fixed name container_name: mongo-crud-web # Automatically restarts the container if it fails restart: on-failure # Tells Docker to start the mongo service before the web service # Note: this does not guarantee MongoDB is fully ready, only that it starts first depends_on: - mongo # Environment variables passed into the Flask application environment: # MongoDB connection string used by the Flask app # The hostname "mongo" works because it is the service name on the Docker network MONGO_URI: mongodb://admin:admin123@mongo:27017/ # MongoDB database name the app should use MONGO_DB_NAME: appdb # MongoDB collection name the app should use MONGO_COLLECTION_NAME: products # Flask secret key used for sessions and flash messages SECRET_KEY: mongo-crud-secret # Port the Flask app listens on inside the container PORT: 8080 # Maps ports between the host machine and the container # Left side = host port, right side = container port ports: - "8080:8080" # Connects the web container to the same Docker network as MongoDB networks: - mongo-crud-net # Defines custom Docker networks used by the application networks: mongo-crud-net: # Explicitly sets the network name instead of letting Docker generate one name: mongo-crud-net # Defines named Docker volumes used by the application volumes: mongo_crud_data: # Explicitly sets the volume name # This volume stores MongoDB files persistently name: mongo_crud_data