-2

I am trying to write ssh keys to docker image using CMD.

I have docker file like below.

FROM public.ecr.aws/ubuntu/ubuntu:18.04_stable
CMD ["sh", "-c", "echo $PUBLIC_KEY >> ./.ssh/id_rsa.pub"]
CMD ["sh", "-c", "echo $PRIVATE_KEY >> ./.ssh/id_rsa"]

I run the container with env var like so:

docker run -it -d -e PUBLIC_KEY="key1" -e PRIVATE_KEY="key2" my-image

As result, writing both of them doesn't work. However, when I manually docker exec these 2 cmd against the running container, it will write both public key and private key to the correct location.

Can anyone explain this? How should I make the CMD work?

2
  • If your application needs ssh keys to run, you should inject them when you run the container; Using SSH keys inside docker container has some advice. You should not use docker exec here (its results will get lost as soon as the container is deleted) and you should definitely not include the keys in your Dockerfile (anyone who has the image can trivially extract them). Commented Oct 24, 2022 at 9:25
  • @DavidMaze I believe I am injecting SSH keys by passing it using env var when running the container. The docker exec is used to see if the env var is received inside docker container. Yes, there is no ssh key in the image since I am passing them into the container using env var. Update the description to make this more clear. Thx for the advice Commented Oct 24, 2022 at 16:19

1 Answer 1

0

CMD is a way to define a default command when starting a container. There can only be one default command. In the example you have given, the second CMD will be the default command, and the first CMD will not run. The default command will run only when you do not specify a command to run on the command line, i.e. as part of the command line

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

if you provide a COMMAND, the CMD in the dockerfile will not be run. When you issue docker exec, you explicitly run the command line, so it will always run.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed the cmd to CMD ["sh", "-c", "echo $PUBLIC_KEY >> ./.ssh/id_rsa.pub; echo $PRIVATE_KEY >> ./.ssh/id_rsa"]. But the ssh keys are still not written into the .ssh folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.