-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?

EzyHoo
  • 301
  • 2
  • 14
  • If your application needs ssh keys to run, you should inject them when you run the container; [Using SSH keys inside docker container](https://stackoverflow.com/questions/18136389/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). – David Maze Oct 24 '22 at 09: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 – EzyHoo Oct 24 '22 at 16:19

1 Answers1

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.

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
  • 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. – EzyHoo Oct 24 '22 at 16:26