Dockerfile vs docker-compose.yml: Understanding the Differences

2 min read
Dockerfile vs docker-compose.yml: Understanding the Differences
Photo by Rubaitul Azad / Unsplash

Docker is a tool that helps you package and deploy applications easily. It uses two main files to manage Docker containers: the Dockerfile and the docker-compose.yml. These files are both important, but they serve different purposes.

Let's start with the Dockerfile

Think of it as a set of instructions for building a Docker image. A Docker image is like a blueprint for a container, which is an isolated environment that runs your application. You can think of a Dockerfile as a recipe for making a Docker image. It tells Docker what base image to use (e.g., Ubuntu), what dependencies to install (e.g., Apache, PHP), and any additional configuration or setup that needs to be done (e.g., copying files, setting environment variables).

Here's an example of a simple Dockerfile:

FROM ubuntu:20.04

RUN apt-get update && apt-get install -y apache2

COPY index.html /var/www/html/

EXPOSE 80

CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

This Dockerfile uses the Ubuntu 20.04 base image and installs Apache. It then copies an HTML file (index.html) to the Apache web root directory and exposes port 80. Finally, it starts Apache in the foreground.

Now let's talk about the docker-compose.yml file

This file is used to define and run multi-container Docker applications. A multi-container Docker application is a group of interconnected containers that work together to run a complete application.

Here's an example of a docker-compose.yml file:

version: '3'
services:
  web:
    build: .
    ports:
      - "80:80"
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: my_database

This docker-compose.yml file defines two services: "web" and "db". The "web" service uses the Docker image built from the current directory (using the instructions in the Dockerfile) and exposes port 80. The "db" service uses the MySQL 5.7 image and sets some environment variables.

To summarize, the Dockerfile is used to build a single Docker image, while the docker-compose.yml is used to define and run multi-container Docker applications. They are both useful in different ways and can help you take full advantage of Docker's containerization capabilities.

Keep the containers up and running!

Harduex blog


Follow