Docker Compose File Structure
In this tutorial we will discuss on how docker compose files work and file structure of docker compose.
version: 'X' services: web: build: . ports: - "8080:8080" volumes: - .:/code redis: image: redis
Now, let’s look at real-world example of a Docker Compose file and break it down step-by-step to understand all of this better.
Note that all the clauses and keywords in this example are commonly used keywords and industry standard. With just these, you can start a development workflow.
There are some more advanced keywords that you can use in production, but for now, let’s just get started with the necessary clauses.
version: '3' services: web: # Path to dockerfile. # '.' represents the current directory in which # docker-compose.yml is present. build: . # Mapping of container port to host ports: - "8080:8080" # Mount volume volumes: - "/home/ashok/docker/app/:/opt/app/" # Link database container to app container for reachability. links: - "database:backenddb" database: # image to fetch from docker hub image: mysql/mysql-server:5.8 # Environment variables for startup script # container will use these variables # to start the container with these define variables. environment: - "MYSQL_ROOT_PASSWORD=root" - "MYSQL_USER=ashok" - "MYSQL_PASSWORD=waytoeasylearn" - "MYSQL_DATABASE=backend" # Mount init.sql file to automatically run and create tables for us. # everything in docker-entrypoint-initdb.d folder # is executed as soon as container is up nd running. volumes: - "/home/ashok/docker/app/db/init.sql:/opt/app/init.sql"
services section defines all the different containers we will create. In our example, we have two services, web and database.
web is the name of our Flask app service. Docker Compose will create containers with the name we provide.
This keyword specifies the location of our Dockerfile, and
. represents the directory where the
docker-compose.yml file is located.
ports keyword is used to map the container’s ports to the host machine. You can also define the port protocol which can either be UDP or TCP.
ports: - "8000:80/udp"
This is just like the
-v option for mounting disks in Docker. In this example, we attach our code files directory to the containers’
/opt/app directory. This way, we won’t have to rebuild the images if changes are made.
This will link one service to another. For the bridge network, we must specify which container should be accessible to which container using links.
If we don’t have a Dockerfile and want to run a service using a pre-built image, we specify the image location using the
image clause. Docker Compose will fork a container from that image.
This keyword allows us to set up an environment variable in the container. This is the same as the
-e argument in Docker when running a container.