Step by step to Docker: How to connect postgres container from Ruby on Rails
You can use postgres container instead of installing postgres for Rails application. This is basic and clear. Because we can download the settings and configurations with postgres image. We can write following command for download the postgres image:
docker pull postgres:latest
Let’s create a container from postgres if downloading successfully completed:
docker run --name CONTAINER_NAME -t -p 0.0.0.0:PORT:5432 -d postgres
Example:
docker run --name postgres_server -t -p 0.0.0.0:5432:5432 -d postgres
If you have already installed postgres, you can’t use the 5432 port number. Because postgress server defaultly using 5432. You can use other port:
Example:
docker run --name postgres_server -t -p 0.0.0.0:2345:5432 -d postgres
Next step is access the postgres command line(you can use pgAdmin with same parameters):
psql -h localhost -p 2345 -U postgres
If connection is successfully complated, let’s change the database.yml file in our rails application as below:
development:
adapter: postgresql
host: localhost
port: 2345
encoding: unicode
database: myapp_development
pool: 5
username: postgres
password: password
We are use default the user for connection. You can create new role/user for application after the connect postgres container as mentioned above.