How to start a specific service when Ubuntu is started on WSL2

Solution 1:

With the recent release of Windows 11, there are two preferred ways to do this.

Windows 11

You can now execute an arbitrary command line when starting an instance by creating/editing /etc/wsl.conf (via sudo) with the following:

[boot]
command="service postgresql start"

This command runs as root and generates no output. If you need to run multiple commands, they should be semicolon separated (or something like &&) inside the command= string.

Windows 10

On WSL with Windows 10, there's still an easier way, IMHO, than putting a sudo command in your startup and worrying about sudoers.

sudoers is certainly the canonical (no pun intended, just a happy accident) way to do it on Ubuntu, but on WSL it's just easier to use the following syntax in your ~/.bashrc:

 wsl.exe -u root service postgresql status || wsl.exe -u root service postgresql start

wsl.exe -u root doesn't require a password. From PowerShell and CMD, it can be called without the exe, but from within WSL it does require the extension.

Note, per @mbomb007's comment, this will generate one or two messages every time you start. To suppress this, use:

wsl.exe -u root service postgresql status > /dev/null || wsl.exe -u root service postgresql start > /dev/null