1. 子系统中编写启动服务脚本

    sudo vim /etc/init.wsl
    例如:
    #! /bin/sh
    # 设置启动服务
    #! /bin/sh
    NUM=`ps -aux | grep mysqld | wc -l`; if [ $NUM -eq 1 ];then service mysql start; fi
    NUM=`ps -aux | grep postgresql | wc -l`; if [ $NUM -eq 1 ];then service postgresql start; fi
    echo ‘ok’

  2. 设置脚本执行权限

    sudo chmod +x /etc/init.wsl

  3. windows中设置(新建wsl2.bat,放在c盘根目录下)

    @echo off
    setlocal enabledelayedexpansionwsl -d Ubuntu-20.04 -u root /etc/init.wsl | findstr “ok” > nul
    if !errorlevel! equ 0 (
    :: set wsl2 ip
    wsl -d Ubuntu-20.04 -u root ip addr | findstr “192.168.169.2” > nul
    if !errorlevel! neq 0 (
    wsl -u root ip addr add 192.168.169.2/28 broadcast 192.168.169.15 dev eth0 label eth0:1
    ):: set windows ip
    ipconfig | findstr “192.168.169.1” > nul
    if !errorlevel! neq 0 (
    netsh interface ip add address “vEthernet (WSL)” 192.168.169.1 255.255.255.240
    )
    )

    window IP:192.168.169.1      wsl2 IP:192.168.169.2

  4. 设置idea编辑器Terminal(设置idea快捷键为管理员启动)

    cmd /k c:\\wsl2.bat && wsl