scalatra + docker (part 6)
Here’s a github repo which will track this project
–
Now that we’ve figured out how to containerize our Scalatra app, let’s get back to developing!
The next step will be preparing a database layer for the API to mirror a real world implementation. For this example I’ve chosen to use Postgres. SQL and therefore Postgres is not the “hottest” DB technology now but I still love it. It reminds me of functional programming in the way that you can compose simple, declarative statements together to do incredibly complex tasks. I’ll say it. SQL is cool.
In this section, we’ll add a Postgres container to our app’s ecosystem and migrate the “greetings” data model off our app and into the database. Let’s do it.
First, we need a docker-compose
file that will handling the spinning up of our Postgres container. Follow along with this previous post to get the details of working with Docker and Postgres.
Here is our docker-compose.yml
for this project:
This will start our container. But, we also need a table and some data so we can run queries against it from our application. As seen in the previous tutorial, we can access files from within the psql
cli. Let’s take advantage of that to run some sql
commands against our database.
We’ll make 2 SQL files: one to create a table, and one to seed it with data.
In create_greetings_table.sql
we will port over our Scala case class Greeting
and add a ID and Timestamp field for good practice.
And in seed_greetings_table.sql
we will plunk down our 4 greetings:
Sweet. Now we just need to bring it all together by making sure every time when our container starts, we have the “migration” scripts run. Sounds like the perfect job for a bash script.
Our script will do the following actions:
- launch Postgres container
- copy over our two sql files
- execute the sql commands in those files using the
psql
cli
Here’s the code:
NOTE: What you see abovde is actually not the most efficient way to accomplish this task. Any files in the container’s docker-entrypoint-initdb.d
directory will actually be auto-run by Docker when a Postgres container is spun up. That would require a slightly different implementation, where we create a dockerfile
and layer our scripts on top before launching a container. I’ll stick with this way for now, but keep that in mind.
Now we’re ready to test.
SUCCESS! Our database now has data and is ready to be interacted with by our Scalatra app. Next time, we will connect our Scala app to Postgres and start doing CRUD operations.