Connecting to Postgres from a Separate Container
We will see how we can connect our database to our Rails app.
Connecting to Postgres
As you become more and more comfortable with using Compose, you will find
that you trust it to do what you need. A quick docker-compose ps
is probably all you need to verify that a service is running. However, since running services like Postgres inside a container is still fairly new for us, let’s take the extra step of manually connecting to it from a different container, just like we did with redis
.
Starting the Postgres client
As was the case with redis
, the postgres
image comes preinstalled with psql, the Postgres client. This means we can piggyback on our new database
service in order to run a one-off container, based on the postgres
image. However, instead of using the default command for the image, which starts the Postgres server, we run a command to start the Postgres client.
Command
We can do this by running the following command:
$ docker-compose run --rm database psql -U postgres -h database
Command explanation
Here we are saying, “Start a new, throwaway container (run --rm
) for the database
service and run the command psql -u postgres -h database
inside it.” This command starts the Postgres client and tells it to connect to the hostname database
with the postgres
user. We are relying on the fact that Compose magically sets up a
network for our application with DNS configured so that the hostname database
will reach the container running our database
service.
Why use run --rm
?
We could have used exec
instead of run --rm
, which would have avoided starting a new container and instead would have executed the command on the database container that is already running. However, we deliberately didn’t because we wanted the extra verification of connecting from a different container.
When you run this command, you will be prompted to enter a password. You need to enter some-long-secure-password
, the password we set in our docker-compose.yml
file. This should be accepted and will take you to the psql
prompt. When you are ready, you can quit the psql
client as follows by typing this:
\q <Enter>
🍀 Practice
Let’s try doing it ourselves.
-
Click the Run button.
-
Start a new, throwaway container connecting the
database
service. -
Quit the psql client.
Get hands-on with 1400+ tech skills courses.