So in the previous post I explained how to get a rails application up and running using Docker. But that project was using SQLite as it’s database.
What if we want to use something else?
In the Dockerfile we had installed the packages to enable us to switch our database to use Postgres. So lets give it a go!
Lets update our Gemfile
So we should probably swap the sqlite3 gem for pg so we can load the postgres database adapter.
And now for our database config
Lets replace all the SQLite stuff in our database.yml file with our postgres settings.
default: &default adapter: postgresql pool: 5 username: postgres host: db development: <<: *default database: my-awesome-app_development test: <<: *default database: my-awesome-app_test production: <<: *default url: <%= ENV['DATABASE_URL'] %>
Now lets set up our Docker Compose configuration
Here is how our docker-compose.yml should look:
version: '2' services: db: image: postgres:9.4.1 ports: - "5432:5432" web: build: . command: bin/rails server --port 3000 --binding 0.0.0.0 ports: - "3000:3000" links: - db volumes: - .:/myapp
Lets get ready to build!
Now we can run
docker-compose build. This will build our containers.
Next we run
docker-compose up to start them.
We are not finished yet though, because if we try and navigate to our rails app we get the following error
This is when we need to run some commands on our running container. This is one of the reasons I use Cmder. I’ll just create a split terminal!
Then we need to run the following commands in order to set up postgres for our rails app:
docker exec -t myawesomeapp_web_1 rails db:setup
docker exec -t myawesomeapp_web_1 rails db:migrate
You will need to restart docker-compose, otherwise rails will not render anything. When you stop docker-compose using Ctrl+C, you will also need to delete tmp\pids\server.pid, otherwise the
rails server command will fail with a message saying that a server is already running.
When you run
docker-compose up again, you should see the following page when you navigate to http://localhost:3000