Search code examples
dockernetwork-programmingclionrti-dds

Start Docker container with host network while maintaining the ability to SSH into the container?


I am starting a local docker container as an environment to run my applications and I use CLion's remote host capabilities to manage the toolchain. My applications communicate on a specific network interface across various ports and ip addresses.

In a perfect world I would be able to run my applications locally and then also start one in a docker container through CLion and communicate with the locally running apps.

I know I can start a docker container with --network=host but that seems to remove the ability to SSH into a docker container which is a prerequisite to using CLion and docker. Is there a way to maintain both? Use the host network but also enable ssh'ing into the docker container?

Snippet from my Dockerfile that configures the SSH agent

########################################################
# Remote debugging and login in
########################################################

RUN mkdir /var/run/sshd
RUN echo 'root:root' | chpasswd
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

# 22 for ssh server. 7777 for gdb server.
EXPOSE 22 7777

RUN useradd -ms /bin/bash debugger
RUN echo 'debugger:pwd' | chpasswd

CMD ["/usr/sbin/sshd", "-D"]

UPDATE: With CLion 2021.3 you no longer need to ssh into your docker container. It is now supported as its own toolchain type https://blog.jetbrains.com/clion/2021/10/clion-2021-3-eap-new-docker-toolchain/#new_docker_toolchain


Solution

  • Using --network=host means that your container will use the hosting machine's port 22 and if the machine already runs a process that uses port 22, the SSH Agent will fail.

    To confirm, you can look at the agent's log files.

    You can configure the SSH Agent to run on a different port than 22 (e.g., 2233), thus avoiding the port collision. In your Dockerfile add the following line:

    RUN sed -i 's/\(^Port\)/#\1/' /etc/ssh/sshd_config && echo Port 2233 >> /etc/ssh/sshd_config
    

    Then configure CLion to connect to the container using the alternative port.