From e0929f7f56e039032cf5eeaafed97e6003c66a2e Mon Sep 17 00:00:00 2001 From: felipecruz91 Date: Tue, 8 Nov 2022 23:42:16 +0100 Subject: [PATCH] Copy network, pid and uts mode only if target container is running --- README.md | 4 ++-- cmd/debug.go | 22 ++++++++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 06d5ad0..6039c16 100644 --- a/README.md +++ b/README.md @@ -66,13 +66,13 @@ Sometimes it's useful to change the entrypoint and/or command for a container, f To simulate a crashing application, use docker run to create a container that immediately exits: ```shell -docker run busybox:1.28 /bin/sh -c "false" +docker run --name crashing-container busybox:1.28 /bin/sh -c "false" ``` You can use `debug-ctr debug` with `--entrypoint` and/or `--cmd` to create a copy of this container with the command changed to an interactive shell: ```shell -debug-ctr debug --image=docker.io/alpine:latest --target=my-distroless --copy-to=my-distroless-copy --entrypoint="/.debugger/sleep" --cmd="365d" +debug-ctr debug --image=docker.io/alpine:latest --target=crashing-container --copy-to=crashing-container-copy --entrypoint="/.debugger/sleep" --cmd="365d" ``` Now you have an interactive shell that you can use to perform tasks like checking filesystem paths or running a container command manually. diff --git a/cmd/debug.go b/cmd/debug.go index b7a67bf..03d4ee4 100644 --- a/cmd/debug.go +++ b/cmd/debug.go @@ -233,6 +233,19 @@ func createCopyContainer(ctx context.Context, debugImage, targetContainer, copyC log.Printf("containerCmd: %+v", containerCmd) target := "container:" + targetContainer + + hostConfig := &container.HostConfig{ + Binds: []string{ + volume + ":" + "/.debugger", + }, + } + + if inspect.State.Running { + hostConfig.NetworkMode = container.NetworkMode(target) + hostConfig.PidMode = container.PidMode(target) + hostConfig.UTSMode = container.UTSMode(target) + } + copyContainerCreateResp, err := cli.ContainerCreate(ctx, &container.Config{ Image: inspect.Image, User: inspect.Config.User, @@ -241,14 +254,7 @@ func createCopyContainer(ctx context.Context, debugImage, targetContainer, copyC Cmd: containerCmd, WorkingDir: inspect.Config.WorkingDir, Labels: inspect.Config.Labels, - }, &container.HostConfig{ - Binds: []string{ - volume + ":" + "/.debugger", - }, - NetworkMode: container.NetworkMode(target), - PidMode: container.PidMode(target), - UTSMode: container.UTSMode(target), - }, nil, nil, copyContainerName) + }, hostConfig, nil, nil, copyContainerName) if err != nil { return err }