Running Commands Inside a Docker Container Without Hardcoding the ID

When working with Docker, you may need to run commands inside a container. A common example is exporting a database with pg_dump from a PostgreSQL container. If your script contains a static container ID, you’ll need to update it after every rebuild, making the process impractical and error-prone.

The problem with a static ID

A container’s ID is generated dynamically each time it’s created. This means that if you hardcode the ID in a script, it will stop working after a rebuild or a restart of the container.

The solution: retrieve the ID dynamically

We can use the docker ps command with the -q option to get only the container ID, and the -f name=... filter to select the container by name.

#!/bin/bash

# Replace "postgres" with the name (or part of the name) of your container
CONTAINER=$(docker ps -qf "name=postgres")

docker exec "$CONTAINER" pg_dump -U username dbname > dbname.sql

How it works

  • docker ps lists the running containers.
  • -q ensures that only the container ID is printed.
  • -f "name=postgres" filters containers by name (can be a partial match).
  • The $CONTAINER variable will hold the selected container’s ID, which is then passed to docker exec.

Advantages of this approach

This method removes the need to manually update the script after each container rebuild. It also makes the code more readable and portable, especially when shared within a team or integrated into automation processes.

Back to top