1

On host machine I have docker-compose stack that have a service called transactions-db its a PostgreSQL container

I want to create a backup service using Golang to be able to create .sql to be used for restores later on

docker-compose.yml for backup service

version: "3.8"

services:
  backup-service:
    build:
      context: .
      dockerfile: Dockerfile
    image: backup-service
    container_name: backup-service
    volumes:
      - .:/app
      - /var/run/docker.sock:/var/run/docker.sock

main.go

package main

import (
    "context"
    "fmt"
    "os"
)

func main () {
    result, err := ExecuteCommandOnContainer(context.Background(), ConnectToDocker(), "transactions-db")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(result.ExitCode)
}

docker.go

package main

import (
    "context"
    "fmt"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client"
)

func ConnectToDocker() *client.Client {
    cli, err := client.NewClientWithOpts()
    if err != nil {
        fmt .Println(err)
    }
    return cli
}
func ExecuteCommandOnContainer(ctx context.Context, cli *client.Client, containerID string) (types.ContainerExecInspect, error) {
    command := []string{"pg_dumpall", "-c", "-U", "user", "|", "gzip", ">", "backup/tr.sql"}
    execConfig := types.ExecConfig{
        Tty:          true,
        AttachStdin:  true,
        AttachStderr: true,
        AttachStdout: true,
        Cmd:          command,
    }
    create, err := cli.ContainerExecCreate(ctx, containerID, execConfig)
    if err != nil {
        fmt .Println(err)
    }

    inspect, err := cli.ContainerExecInspect(ctx, create.ID)
    if err != nil {
        fmt .Println(err)
    }
    return inspect, nil
}

basically nothing happens when I run this code. I only get the following:

backup-service | 0 backup-service exited with code 0

I tried to normally run: go run . I've also tried using my docker-compose up same result

note: I've tested listing container it works but when trying to execute a command nothing

  • I don't think the `pg_dumpall` command understands `|` or `>` as options. I'd suggest compressing and writing the output in Go code rather than trying to construct a shell pipeline. (Better still would be to run `pg_dumpall` on the host, avoiding any Docker-specific logic.) – David Maze Jun 10 '22 at 14:06

0 Answers0