How to use SSH keys inside docker container ?

Better Stack Team
Updated on April 14, 2023

To use SSH keys inside a Docker container, you can follow these steps:

  1. If you haven't already done so, you need to generate an SSH key pair. You can do this using the ssh-keygen command on your local machine:

     
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    

    This command will generate a new SSH key pair with a 4096-bit RSA key and the specified email address as the comment.

  2. To use the SSH key inside the container, you need to add the private key to the container's file system. You can do this using a Docker volume, which allows you to mount a directory on your local machine as a directory inside the container.

    For example, you can run the following command to start a new container and mount the directory containing your SSH private key as a volume inside the container:

     
    docker run -it -v /path/to/private/ssh/key:/root/.ssh my-image
    

    Replace /path/to/private/ssh/key with the path to the directory containing your private SSH key, and my-image with the name of the Docker image you want to run.

  3. By default, SSH requires that private key files have restrictive permissions to prevent unauthorized access. To set the correct permissions on the private key file, you can run the following command inside the container:

     
    chmod 600 /root/.ssh/id_rsa
    

    Replace /root/.ssh/id_rsa with the path to your SSH private key file.

  4. Once you have added the SSH private key to the container, you need to configure SSH to use the key when connecting to remote hosts. You can do this by creating a config file in the ~/.ssh/ directory inside the container.

    For example, you can run the following command to create a new config file inside the container:

     
    echo "Host my-remote-host\n\tIdentityFile /root/.ssh/id_rsa" > /root/.ssh/config
    

    Replace my-remote-host with the hostname or IP address of the remote host you want to connect to.

  5. Once you have configured SSH to use the private key, you can test the connection by running the ssh command inside the container:

     
    ssh my-remote-host
    

    This will attempt to connect to the remote host using the SSH key you added to the container. If the connection is successful, you should see a prompt for the remote host's command line.

Note: When using SSH keys inside a Docker container, it's important to make sure that the private key file is kept secure and not shared with other users or containers.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →