Last episode was about dockerizing our Ruby on Rails app. In this episode we’ll be exploring how to perform everyday tasks in our containers.
Running rake tasks and rails commands
Running rake tasks is easy. Once you’ve built your images, you can use
docker-compose to run commands in them. For example, if you want to see the routes of your app:
$ docker-compose run web rails routes
Similarly, if you want to create the db, migrate and seed:
$ docker-compose run web rails db:create db:migrate db:seed
If, instead, you want to run your test suite, you’ll have to create the test db:
$ docker-compose run web rails db:create db:migrate RAILS_ENV=test
and then run the test suite (assuming rake defaults to rake test):
$ docker-compose run web rake
Tip: create your custom scripts/aliases
docker-compose run web rails ... hundred times a day, so to make things easier I put this script in my
#!/bin/bash docker-compose run web rails "$@"
Note that this script assumes your
docker-compose.yml file has a
web service. If you don’t it won’t work.
Performing other tasks
So far, all commands are quite straigthforward, you just run them within the
web service. What happens with somewhat harder tasks such as loading a pre-existing database into your container’s database? This is one of the tasks that took me longer to figure out.
In postgres there are 2 ways of doing this and it depends on the dump’s format. In the past we had to deal with
--format=c dumps and regular dumps.
Assuming you have a
latest.dump file that contains a postgres dump in
c format, and you want to load it in your (running) container, you first have to figure out what your container id is. You can do that by running:
$ docker container ls
$ docker ps
Once you have the container id (in this example we’ll use
80f8041db4b4), you can run this command to restore the dump in the container:
$ docker exec -i 80f8041db4b4 pg_restore -d app_development -U postgres < latest.dump
If instead you’d have a regular dump (eg.
latest.sql), you can run this command to restore it:
$ docker exec -i 80f8041db4b4 psql -d app_development -U postgres < latest.sql
If you’re using
docker-compose, things get easier:
$ docker-compose exec -T db pg_restore -d app_development -U postgres < latest.dump
I use elasticbeanstalk a lot. I usually install it with homebrew, but it installs a bunch of dependencies of its own, like python, sqlite, etc. I don’t want all of that in my system, specially because I always have troubles with python versions. Instead, I dockerized it: docker-awsebcli.
Join us in the next episode!