I need to run sudo service postgresql start every time when I start Ubuntu on WSL2.
How can I make the service start automatically when I start Ubuntu?
WSL doesn't use systemd, so sudo systemctl enable postgresql doesn't work.
$ sudo systemctl status postgresql
System has not been booted with systemd as init system (PID 1).
Can't operate. Failed to connect to bus: Host is downIs there a standard way to start a service at startup?
Edit
I want to start the service on Ubuntu startup, not on Windows startup.
61 Answer
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 startwsl.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 5