duanlan7239
duanlan7239
2017-09-22 04:42

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

已采纳

I'm trying to call docker's mysqldump from host system for save mysql dump from golang. It works correctly with host mysqldump, but don't work with docker's 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)
   }

}

I got only that for non-empty database empty mysql dump

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • donglian8407 donglian8407 4年前

    The solution is:

    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)
    }
    

    }

    Just without "> dbname.sql"

    点赞 评论 复制链接分享
  • douzhulv1699 douzhulv1699 4年前

    EDIT:

    The OP doesn't work inside go code. It gives an error: the input device is not a TTY. I will try to find out why and update the post...


    OP:

    What about using docker exec -it [command]

    Example:

    # start a new mysql container...
    $ docker run --rm -d --name="test_mysql" -e MYSQL_ROOT_PASSWORD=root mysql
    
    # mysqldump > stdout
    $ docker exec -it test_mysql mysqldump -u root -proot sys
    

    or

    # mysqldump > stdout > file
    $ docker exec -it test_mysql mysqldump -u root -proot sys > sys.sql
    
    点赞 评论 复制链接分享
  • donglu6805 donglu6805 4年前

    Instead of mysql, try a simple command like :

    • pwd
    • echo a > b, just to see if you do see a file b on your host.

    You need to make that redirection inside the container in a folder which has been mounted from the host (using volume), in order for the created file to persists, once docker exec exits the container.

    点赞 评论 复制链接分享