Start PostgreSQL on WSL Startup

Sean Morrison
Pixel and Ink
Published in
2 min readMay 25, 2022

Writing a mini-blog for something which was annoying me with my local dev setup and constant forgetting to boot PostgreSQL.

The Problem

Starting Postgresql assumes you’re running as root or someone who can chmod the /var/run/postgresql folder

So we want to make it so our local unprivilged user can first start the service and then modify the folder permissions.

Solution

First you want to enable running service postgresql start as a non-root user. Open WSL and run sudo visudo

Add the following to the end of the file, exit and save

%sudo   ALL=(ALL) NOPASSWD: /usr/sbin/service postgresql start

Once done we need to fix some permissions so your user can modify the Postgres socket folder.

Run sudo chown $USER /var/run/postgresql/

WARNING: This means only your WSL user will be able to start PostgreSQL. Considering this is your WSL install I can’t imagine a usecase where someone else needs to start it, so just consider this a warning

Finally edit your ~/.bashrc file and add this to the end

# Check if postgresql is running and boot it if not
ps aux | grep ‘[p]ostgresql’ &> /dev/null && echo ‘+++Postgresql Running’ || (echo ‘ — — Postgresql not started, attempting to start…’; sudo service postgresql start)

The first time you open WSL you’ll be notified it isn’t running and should see it start up.

If it’s running you’ll get a little console output letting you know it’s running

It’s a bit of a hack, but it might save you some time!

--

--