WSL2 上启动 Ubuntu 时如何启动特定服务

iro*_*and 21 startup services windows-subsystem-for-linux

sudo service postgresql start每次在 WSL2 上启动 Ubuntu 时都需要运行。

如何让该服务在启动Ubuntu时自动启动?

WSL 不使用 systemd,因此sudo systemctl enable postgresql不起作用。

$ 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
Run Code Online (Sandbox Code Playgroud)

是否有在启动时启动服务的标准方法?

编辑

我想在 Ubuntu 启动时启动该服务,而不是在 Windows 启动时启动该服务。

Not*_*1ds 29

随着最近发布的 Windows 11,有两种首选方法可以实现此目的。

视窗11

/etc/wsl.conf现在,您可以通过使用以下命令创建/编辑(通过 sudo)来启动实例时执行任意命令行:

[boot]
command="service postgresql start"
Run Code Online (Sandbox Code Playgroud)

此命令以 root 身份运行并且不生成任何输出。如果您需要运行多个命令,它们应该在字符串&&内用分号分隔(或类似的内容)command=

Windows 10

在 Windows 10 的 WSL 上,恕我直言,还有一种更简单的方法,比sudo在启动中放置命令并担心sudoers.

sudoers当然是在 Ubuntu 上执行此操作的规范(没有双关语,只是一个愉快的意外)方法,但在 WSL 上,在您的 中使用以下语法更容易~/.bashrc

 wsl.exe -u root service postgresql status || wsl.exe -u root service postgresql start
Run Code Online (Sandbox Code Playgroud)

wsl.exe -u root不需要密码。从 PowerShell 和 CMD 中,可以在不使用 的情况下调用它exe,但从 WSL 中,它确实需要扩展。

请注意,根据@mbomb007的评论,每次启动时都会生成一两条消息。要抑制这种情况,请使用:

wsl.exe -u root service postgresql status > /dev/null || wsl.exe -u root service postgresql start > /dev/null
Run Code Online (Sandbox Code Playgroud)

  • 为了避免每次打开 WSL 时都看到输出,请使用 `wsl.exe -u root service postgresql status > /dev/null || wsl.exe -u root service postgresql start > /dev/null` 代替。 (2认同)