Build images before starting containers
In the previous steps, we used pre-built Docker images from Docker Hub (like nginx:latest). However, you will often need to build your own custom Docker images for your applications.
Docker Compose can automatically build images defined in your docker-compose.yml file before starting the services. This is typically done by specifying a build context instead of an image name for a service.
Let's modify our docker-compose.yml file to build a simple custom Nginx image.
First, create a new directory named nginx_custom inside ~/project.
cd ~/project
mkdir nginx_custom
Now, create a Dockerfile inside the nginx_custom directory.
nano ~/project/nginx_custom/Dockerfile
Add the following content to the Dockerfile:
FROM nginx:latest
RUN echo '<h1>Hello from Custom Nginx!</h1>' >/usr/share/nginx/html/index.html
This Dockerfile starts from the official nginx:latest image and then replaces the default index.html file with a custom one.
Next, modify your ~/project/docker-compose.yml file to use this Dockerfile for building the web service image. Open the file for editing:
nano ~/project/docker-compose.yml
Change the web service definition to use build instead of image:
version: "3.8"
services:
web:
build: ./nginx_custom
ports:
- "80:80"
Now, when you run docker compose up, Docker Compose will first build the image defined by the Dockerfile in the ./nginx_custom directory and then start a container using that newly built image.
Make sure you are in the ~/project directory and run:
cd ~/project
docker compose up -d
You will see output indicating that Docker Compose is building the image and then creating and starting the container.
To verify that the custom Nginx page is being served, use curl:
curl http://localhost
You should see the output <h1>Hello from Custom Nginx!</h1>, confirming that the image was built and the container is running with the custom content.
To clean up, stop the running services:
cd ~/project
docker compose down