9.4.4.3 Exec Database CLI
A focused guide to Exec Database CLI, connecting core concepts with practical Docker and container operations.
Exec database CLI uses docker compose exec to run a database's own command-line client directly inside its running container, providing direct, interactive database access without needing a separately installed client on the host machine.
Connecting to a PostgreSQL Database
The database's own client tool, already present inside its image, connects directly within the container.
docker compose exec db psql -U postgres -d myapp
This opens an interactive psql session, connected to the running database, without requiring psql to be separately installed on the host.
Connecting to a MySQL Database
The equivalent client for a different database engine works the same way.
docker compose exec db mysql -u root -p myapp
Running a Single Query Without an Interactive Session
A specific query can be executed directly, with its result returned immediately, rather than opening a full interactive session.
docker compose exec db psql -U postgres -c "SELECT count(*) FROM users;"
Why This Approach Avoids Host-Side Client Installation
Without this approach, directly querying a containerized database from the host would require installing that specific database's client tools locally — running the client through exec instead relies on the tooling already present inside the database's own image.
docker compose exec db pg_dump -U postgres myapp > backup.sql
Even more involved database operations, like producing a dump, can be run this same way, using the tooling already available inside the container.
Why Exec Database CLI Matters
This pattern provides convenient, direct database access for inspection, querying, and administrative tasks, without the overhead of separately installing and maintaining database client tools on the host machine for every database technology a project might use.