Start a sample Compose project
In this step, we will learn how to start a sample Compose project. Before we can use Docker Compose, we need to install it. Since the LabEx VM environment does not have Docker Compose pre-installed, we will install it first.
We will download the Docker Compose binary and make it executable.
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
After the installation, we can verify the installation by checking the version of Docker Compose.
docker-compose --version
You should see the version information printed to the console, confirming that Docker Compose is installed correctly.
Now, let's create a simple Compose project. We will create a directory for our project and then create a docker-compose.yml
file inside it. This file will define the services for our application.
First, create a directory named my-compose-app
.
mkdir ~/project/my-compose-app
cd ~/project/my-compose-app
Next, create a file named docker-compose.yml
in the ~/project/my-compose-app
directory using the nano
editor.
nano docker-compose.yml
Add the following content to the docker-compose.yml
file. This file defines a single service named web
that uses the nginx
image.
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "80:80"
Save the file and exit the nano
editor (Press Ctrl + X
, then Y
, then Enter
).
Before starting the service, we need to make sure the nginx:latest
image is available locally. We can pull the image using the docker pull
command.
docker pull nginx:latest
Now that we have the docker-compose.yml
file and the necessary image, we can start the Compose project using the docker-compose up
command. The -d
flag runs the services in detached mode, meaning they will run in the background.
docker-compose up -d
This command will create and start the web
service as defined in the docker-compose.yml
file. You should see output indicating that the service is being created and started.
To verify that the service is running, you can use the docker ps
command to list the running containers. You should see a container for the web
service.
docker ps
You can also access the Nginx web server by opening a web browser and navigating to the IP address of your LabEx VM. Since we mapped port 80 of the container to port 80 of the host, you should see the default Nginx welcome page.