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
sudo service postgresql startin your.bashrcshould work fine.) – muru Aug 03 '21 at 02:29sudocommand in.bashrc. In that way I always need to type my password when I open new tabs. – ironsand Aug 04 '21 at 03:20ironsand ALL=NOPASSWD:/usr/sbin/service postgresqlto/etc/sudoerand restart wsl, but I still need to enter password every time. Maybe this is another question, should I open a new question? – ironsand Aug 05 '21 at 10:40sudo service postgresql!=sudo service postgresql start. Try adding thestartto the sudoers line as well. You shouldn't have to restart WSL, changes tosudoerstake effect immediately. – muru Aug 05 '21 at 12:19