The Go fail to exec "wsl sudo service docker start" while powershell can run it

63 Views Asked by At

Here is my .go file

package config

import (
    "log"
    "os/exec"
)

func StartWSLContainers() {
    // Test if we can invoke WSL commands
    if err := exec.Command("wsl", "echo", "hello").Run(); err != nil {
        log.Fatalf("Failed to use WSL command: %v", err)
    }

    // Start the Docker service
    if err := exec.Command("wsl", "sudo", "service", "docker", "start").Run(); err != nil {
        log.Fatalf("Failed to start Docker service: %v", err)
    }

    // Start containers based on the conf/docker-compose.yml file
    if err := exec.Command("wsl", "docker-compose", "-f", "conf/docker-compose.yml", "up", "-d").Run(); err != nil {
        log.Fatalf("Failed to start docker-compose: %v", err)
    }
}

The result is the error message:

C:\Users\test\AppData\Local\JetBrains\GoLand2023.2\tmp\GoLand\___2go_build_main_go.exe
time="2023-11-27T21:30:40+08:00" level=info msg="config === {AppConfig:{AppName:user_system Version:v1.0.1 Port:8080 RunMode:release} CorsOrigin:[*.trovo.live] DbConfig:{Host:0.0.0.0 Port:8086 User:root Password:123456 Dbname:camps_user MaxIdleConn:5 MaxOpenConn:20 MaxIdleTime:300} LogConfig:{LogPattern:file LogPath:./log/server.log SaveDays:5 Level:info} RedisConfig:{Host:0.0.0.0 Port:8089 DB:0 PassWord: PoolSize:100} Cache:{SessionExpired:7200 UserExpired:300}}"
2023/11/27 21:30:40 Failed to start docker service: exit status 1

Process finished with the exit code 1


I have given GoLand administrator privilege,and test the command works well in powershell.

1

There are 1 best solutions below

0
On
package config

import (
    "log"
    "os/exec"
)

func StartWSLContainers() {
    // Test if we can invoke WSL commands
    if err := exec.Command("wsl", "echo", "hello").Run(); err != nil {
       log.Fatalf("Failed to use WSL command: %v", err)
    }

    // Start the Docker service only if it's not running
    if err := exec.Command("wsl", "service", "docker", "start").Run(); err != nil {
       //check the status of docker
       if err := exec.Command("wsl", "service", "docker", "status").Run(); err != nil {
          log.Fatalf("Failed to start docker service: %v", err)
       } else {
          log.Printf("docker service already started")
       }
    } else {
       log.Printf("docker service started")
    }

    // Start containers based on the conf/docker-compose.yml file
    ymlPath := "/mnt/c/****/Backend Projects/user_system/conf/docker-compose.yml" 
    // docker-compose can automatically choose its behavior based on the container's status
    if err := exec.Command("wsl", "docker-compose", "-f", ymlPath, "up", "-d").Run(); err != nil {
       log.Fatalf("Failed to start docker-compose: %v", err)
    } else {
       log.Printf("docker-compose finished successfully")
    }
}