Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  27] [ 0]  / answers: 1 / hits: 21181  / 1 Year ago, mon, february 20, 2023, 10:18:50

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 down

Is there a standard way to start a service at startup?


Edit


I want to start the service on Ubuntu startup, not on Windows startup.


More From » startup

 Answers
7

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

[#1292] Tuesday, February 21, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
scusaper

Total Points: 335
Total Questions: 111
Total Answers: 119

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
scusaper questions
Fri, Apr 15, 22, 15:26, 2 Years ago
Wed, Mar 15, 23, 03:53, 1 Year ago
Sat, Jun 4, 22, 18:03, 2 Years ago
Wed, Apr 6, 22, 00:55, 2 Years ago
;