DEV Community

Cover image for How to set up a development env to Rails app with Docker and PostgreSQL on WSL2
Clever Lopes
Clever Lopes

Posted on • Edited on

2

How to set up a development env to Rails app with Docker and PostgreSQL on WSL2

For development, I don't guess configuring Dockerfile and docker-compose (just if you want, sure) is necessary.

Pre-reqs

This short tutorial was built using WSL2, integrated docker, ruby 3.2.2 and rails 7.0.6.

Getting Started

We're going to basically create a new rails application, raise and connect the docker postgresql container with the app.

I like creating my projects in ~/projects
$ mkdir ~/projects && cd projects
$ rails new myapp -d postgresql

You don't need the postgresql installed, just the necessary packages to run it. If you have a problem with the pg gem, make sure the following packages are installed.

on ubuntu
$ sudo apt-get install libpq-dev

on arch $ yay -S postgresql-libs or just $ sudo pacman -S postgresql-libs

After this, you can raise the container with the postgres replacing the {} for the name that you want.

$ docker run --name {container_name} -e POSTGRES_PASSWORD={password} -e POSTGRES_USER={username} -p 5432:5432 -v $HOME/docker/volumes/postgres:/var/lib/postgresql/data -d postgres:14.2-alpine

This command will raise the container binding the 5432 port and setting the volume, you can change the postgres:14.2-alpine for another image.

Now you have to set the /config/database.yml with the right params to connect in the postgres container.

Your file will be like this:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost
  port: 5432
  password: {your_password}
  username: {your_username}

development:
  <<: *default
  database: {myapp_development_db}

test:
  <<: *default
  database: {myapp_test_db}

production:
  <<: *default
  database: {myapp_production_db}
  username: {your_prod_username}
  password: {your_prod_password}
Enter fullscreen mode Exit fullscreen mode

I put the password and username in default, but the best is to have a user and password for the dev, test and prod. And put all the values on a .env file.

If all occur well you just have to run
$ rails s
and you can start your app development.

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started