docker-compose: accessing postgres' shell (psql)
Let's start with a minimal docker-compose.yml
file for reference:
version: "3"
services:
postgres:
image: postgres:9.5
You bring your services up with docker-compose up
.
Let's assume you have a database you want to connect to called test
.
Answer: docker-compose run --rm postgres psql -h YOUR_SERVICE -U YOUR_USER -d YOUR_DATABASE
The --rm
option removes the container after exit, so you don't create unnecessary duplicate containers just for accessing the database.
In our example, this would be docker-compose run --rm postgres psql -h postgres -U postgres -d test
Alternatively, you could use psql's connection string: docker compose run --rm postgres psql -d postgres://YOUR_USER@YOUR_SERVICE/YOUR_DATABASE
Things have changed a bit since the question was originally asked.
Here's how you can access PostgreSQL's shell (psql) using docker-compose today:
- Use a docker-compose.yml version '2' config file
- Use 'depends_on' rather than 'links' (new to version '2')
- Break up your containers using 'services'
docker-compoose.yml
version: '2'
services:
postgresdb:
build: utils/sql/
ports:
- "5432"
environment:
- DEBUG=true
main:
build: .
volumes:
- .:/code
depends_on:
- postgresdb
environment:
- DEBUG=true
In your docker engine shell ...
- Find the container id (or container name) from the
docker ps
command - Use that id to open a shell prompt
- Switch user to the postgres user account
- Run psql
See example below:
## .
## ## ## ==
## ## ## ## ## ===
/"""""""""""""""""\___/ ===
~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ / ===- ~~~
\______ o __/
\ \ __/
\____\_______/
_ _ ____ _ _
| |__ ___ ___ | |_|___ \ __| | ___ ___| | _____ _ __
| '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
| |_) | (_) | (_) | |_ / __/ (_| | (_) | (__| < __/ |
|_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|
Boot2Docker version 1.11.2, build HEAD : a6645c3 - Wed Jun 1 22:59:51 UTC 2016
Docker version 1.11.2, build b9f10c9
docker@default:~$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b563764171e2 poc_web "bundle exec rails s " 43 minutes ago Up 43 minutes 0.0.0.0:3000->3000/tcp poc_web_1
c6e480b0f26a postgres "/docker-entrypoint.s" 49 minutes ago Up 49 minutes 0.0.0.0:5432->5432/tcp poc_db_1
docker@default:~$ docker exec -it c6e480b0f26a sh
# su - postgres
No directory, logging in with HOME=/
$ psql
psql (9.5.3)
Type "help" for help.
postgres=#
Notes:
- docker-compose up will start services in dependency order
If you want to stand up a postgres container using the official image, you docker-compose.yml might look more like the following:
version: '2' services: db: image: postgres ports: - "5432:5432" . . .
References
https://docs.docker.com/compose/compose-file/