List running containers with docker compose ps
In this step, you will learn how to list running containers using docker compose ps
. Before we can use docker compose
, we need to install it.
First, let's install Docker Compose. We will download the latest stable release.
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
This command downloads the Docker Compose binary for your system's architecture and saves it to /usr/local/bin/docker-compose
.
Next, we need to apply executable permissions to the binary.
sudo chmod +x /usr/local/bin/docker-compose
Now, let's verify the installation by checking the version.
docker-compose --version
You should see the installed version of Docker Compose in the output.
To demonstrate docker compose ps
, we need a docker-compose.yml
file and some services to run. Let's create a simple docker-compose.yml
file in your ~/project
directory.
nano ~/project/docker-compose.yml
Add the following content to the file:
version: "3.8"
services:
web:
image: nginx:latest
ports:
- "80:80"
app:
image: alpine:latest
command: sleep infinity
This docker-compose.yml
file defines two services: web
using the nginx
image and app
using the alpine
image. The web
service maps port 80 on the host to port 80 in the container. The app
service runs the sleep infinity
command to keep the container running.
Save the file and exit the editor (Ctrl+X, Y, Enter).
Now, let's pull the necessary images.
docker pull nginx:latest
docker pull alpine:latest
These commands download the nginx:latest
and alpine:latest
images from Docker Hub.
Next, start the services defined in the docker-compose.yml
file. Make sure you are in the ~/project
directory.
cd ~/project
docker-compose up -d
The docker-compose up -d
command builds, creates, starts, and attaches to containers for a service. The -d
flag runs the containers in detached mode, meaning they run in the background.
Now that the containers are running, we can use docker compose ps
to list them.
docker-compose ps
This command lists the running containers defined in your docker-compose.yml
file. You should see output similar to this, showing the container names, commands, status, and ports.
NAME COMMAND SERVICE STATUS PORTS
project-app-1 "sleep infinity" app running
project-web-1 "/docker-entrypoint.sh nginx -g 'daemon off;'" web running 0.0.0.0:80->80/tcp
The output shows the project-app-1
and project-web-1
containers are running. The NAME
is typically the project name (the directory name) followed by the service name and a number.