Installing PostgreSQL with Windows Subsystem Linux (WSL2)
My first language was Ruby and when I learned Ruby on Rails, I was developing with SQLite3. However, when I went to begin deploying apps to Heroku, I quickly found out I would need to use PostgreSQL. For some reason, I struggled to find easy instructions for installing PostgreSQL for WSL2 users (I have a Mac as well and it was much easier). So I finally found a couple of various instructions and put together easy-to-understand instructions on how to install PostgreSQL on WSL2.
Remove Previous PostgreSQL packages
If you are using WSL2, most likely you are using Ubuntu, so begin by opening up your Ubuntu terminal.
In case you have tried to install Postgres previously, let’s clean up any previous installs
sudo apt-get remove postgresql
This should be enough, however, I have linked some articles below if you want to truly purge all PostgreSQL from your system.
- https://askubuntu.com/questions/32730/how-to-remove-postgres-from-my-installation
- https://www.liquidweb.com/kb/how-to-remove-postgresql/
Installing PostgreSQL
Now, we can go ahead and install Postgres with it’s development libraries
sudo apt install postgresql postgresql-contrib libpq-dev
NOTE: after first install, and anytime you restart your machine, you will have to restart the Postgres service. Otherwise, you will receive an error about if the server is running.
To start the server, type
sudo service postgresql start
Create New Database Role / User
After starting the Postgres Server, we need to create a new database role, which allows user permissions and authorization. The following will create a superuser role to allow you to operate within the PostgreSQL system and create databases.
NOTE: where it says <username_here>, substitute with your Ubuntu username. The “-P” flag will prompt you to enter a password for the role. Enter in a password (the Ubuntu terminal will not display anything but it is registering the keystrokes) and then re-enter the password when prompted.
sudo -u postgres createuser -s username_here -P
And BOOM! You are set up and ready to use PostgreSQL in your next Ruby on Rails application. If you want Ruby on Rails to use Postgres for development and production, use the database flag
rails new my-app-name -d=postgresql
And before you do any migrations, make sure to create the database first
rails db:create
Happy Coding!