Prepare a simple multi-service application
In this step, we will prepare a simple multi-service application that we will use throughout this lab to practice restarting Docker services. This application consists of two services: a web service and a database service. We will define these services using a Docker Compose file.
First, we need to install Docker Compose. Since it's not pre-installed in the LabEx VM environment, we will download and install it.
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
The first command downloads the Docker Compose binary from the official GitHub repository and saves it to /usr/local/bin/docker-compose
. The $(uname -s)
and $(uname -m)
parts automatically detect your operating system and architecture to download the correct binary. The second command makes the downloaded file executable.
Now, let's verify the installation by checking the Docker Compose version.
docker-compose --version
You should see output similar to Docker Compose version v2.20.2
.
Next, navigate to the ~/project
directory, which is your working directory for this lab.
cd ~/project
Now, we will create a docker-compose.yml
file to define our multi-service application. This file will specify the services, their images, and any necessary configurations.
nano docker-compose.yml
Paste the following content into the docker-compose.yml
file:
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "80:80"
depends_on:
- db
db:
image: postgres:latest
environment:
POSTGRES_PASSWORD: mysecretpassword
In this docker-compose.yml
file:
version: '3.8'
specifies the Docker Compose file format version.
services:
defines the different services in our application.
- The
web
service uses the nginx:latest
image, maps port 80 on the host to port 80 in the container, and depends on the db
service. This means the db
service will be started before the web
service.
- The
db
service uses the postgres:latest
image and sets the POSTGRES_PASSWORD
environment variable, which is required by the PostgreSQL image.
Save the file and exit the nano editor (Press Ctrl + X
, then Y
, then Enter
).
Before starting the services, we need to pull the necessary Docker images.
docker pull nginx:latest
docker pull postgres:latest
These commands download the nginx:latest
and postgres:latest
images from Docker Hub.
Finally, let's start the services defined in our docker-compose.yml
file.
docker-compose up -d
The docker-compose up -d
command builds, creates, and starts the services in the background (detached mode).
You can check the status of the running services using the following command:
docker-compose ps
You should see output indicating that both the web
and db
services are running.