The result of docker exec command

2020-06-08 13:37发布

问题:

I need to know in my shell script the output of some docker exec commands, for example I have an nginx container and in my script I run:

docker exec -it containerName /etc/init.d/nginx configtest

I want to continue script execution only if nginx config test is success, not when fail.

I've tried out to use $?, but it is 0 even then configtest output is fail (because docker exec is successfully executed, as I understand).

回答1:

I found this to be working quite well:

docker exec -t -i my-container sh -c 'my-command; exit $?'


回答2:

Translating my comment into an answer. This should work:

docker exec -it mynginx /etc/init.d/nginx configtest && echo "pass" || echo "fail"

It works for me.



回答3:

The api/client/exec.go#L97-L100 does get the exit code:

var status int
if _, status, err = getExecExitCode(cli, execID); err != nil {
    return err
}

That comes from api/client/utils.go#L84-L97

// getExecExitCode perform an inspect on the exec command. It returns
// the running state and the exit code.
func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
    resp, err := cli.client.ContainerExecInspect(execID)
    if err != nil {
        // If we can't connect, then the daemon probably died.
        if err != lib.ErrConnectionFailed {
            return false, -1, err
        }
        return false, -1, nil
    }

    return resp.Running, resp.ExitCode, nil
}

So if your command fail, you will get the exit code.
Although, as mentioned here, you could use nginx -t instead of configtest.