小编典典

如何将标准输出从Docker容器重定向到主机

go

我正在尝试从主机系统调用docker的mysqldump,以从golang保存mysql
dump。它可以与主机mysqldump正常工作,但不能与docker的mysqldump一起工作。

func writeDb(dbName string)
{
   var mysqldumpPath string = "/usr/bin/mysqldump"
 //var mysqldumpPath string = "/Applications/MAMP/Library/bin/mysqldump"

 //cmd := exec.Command(mysqldumpPath, fmt.Sprintf("-u%s", USER), fmt.Sprintf("-p%s", PASSWORD) , dbName)
   cmd := exec.Command("docker", "exec", "some-mysql", mysqldumpPath, fmt.Sprintf("%s", USER), fmt.Sprintf("-p%s", PASSWORD) , dbName, ">", fmt.Sprintf("%s.sql", dbName))

   stdout, err := cmd.StdoutPipe()
   if err != nil
   {
     log.Fatal(err)
   }

   if err := cmd.Start(); err != nil
   {
     log.Fatal(err)
   }

   bytes, err := ioutil.ReadAll(stdout)
   if err != nil
   {
      log.Fatal(err)
   }
   err = ioutil.WriteFile("./backup/" + dbName +".sql", bytes, 0644)
   if err != nil
   {
     panic(err)
   }

}

我只有非空数据库的 空mysql dump


阅读 655

收藏
2020-07-02

共1个答案

小编典典

解决方案是:

func writeDb(dbName string) {
var mysqldumpPath string = "/usr/bin/mysqldump"
cmd := exec.Command("docker", "exec", "some-mysql", mysqldumpPath, "-u", fmt.Sprintf("%s", USER), fmt.Sprintf("-p%s", PASSWORD) , fmt.Sprintf("%s", dbName))

stdout, err := cmd.StdoutPipe()
if err != nil {
    log.Fatal(err)
}

if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

bytes, err := ioutil.ReadAll(stdout)
if err != nil {
    log.Fatal(err)
}
err = ioutil.WriteFile("./backup/" + dbName +".sql", bytes, 0644)
if err != nil {
    panic(err)
}

}

没有“> dbname.sql”

2020-07-02