Search code examples
dockersshdocker-containeripv4nvidia-docker

How to access to a docker container via SSH using IP address?


I'm using NVIDIA Docker in a Linux machine (Ubuntu 20.04). I've created a container named user1 using nvidia/cuda:11.0-base image as follows:

docker run --gpus all --name user1 -dit nvidia/cuda:11.0-base /bin/bash

And, here is what I see if I run docker ps -a:

admin@my_desktop:~$ docker ps -a
CONTAINER ID   IMAGE                                  COMMAND                  CREATED          STATUS                     PORTS     NAMES
a365362840de   nvidia/cuda:11.0-base                  "/bin/bash"              3 seconds ago    Up 2 seconds                         user1

I want to access to that container via ssh using its unique IP address from a totally different machine (other than my_desktop, which is the host). First of all, is it possible to grant each container a unique IP address? If so, how can I do it? Thanks in advance.


Solution

  • In case you want to access to your container with ssh from an external VM, you need to do the following

    1. Install the ssh daemon for your container
    2. Run the container and expose its ssh port

    I would propose the following Dockerfile, which builds from nvidia/cuda:11.0-base and creates an image with the ssh daemon inside

    Dockerfile

    # Instruction for Dockerfile to create a new image on top of the base image (nvidia/cuda:11.0-base)
    FROM nvidia/cuda:11.0-base
    ARG root_password
    RUN apt-get update || echo "OK" && apt-get install -y openssh-server
    RUN mkdir /var/run/sshd
    RUN echo "root:${root_password}" | chpasswd
    RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
    RUN sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config
    EXPOSE 22
    CMD ["/usr/sbin/sshd", "-D"]
    

    Build the image from the Dockerfile

    docker image build --build-arg root_password=password --tag nvidia/cuda:11.0-base-ssh .
    

    Create the container

    docker container run -d -P --name ssh nvidia/cuda:11.0-base-ssh
    

    Run docker ps to see the container port

    enter image description here

    Finally, access the container

    ssh -p 49157 root@<VM_IP>
    

    EDIT: As David Maze correctly pointed out. You should be aware that the root password will be visible in the image history. Also this way overwrites the original container process.

    This process, if it is to be adopted it needs to be modified in case you need it for production use. This serves as a starting point for someone who wishes to add ssh to his container.