How to create a SSH-enabled docker image on WSL2

Tony Qu
2 min readNov 27, 2021

--

I’m working on a task which enables IntelliJ remote development on container these days. We have an existing Docker image for centos 7. To make remote debugging working on IntelliJ, I have to enable SSH on this image first.

After some investigation, the major task is to install sshd service on the container and make it work as a backend service. However, to make systemctl command work as expected, we have to use a new docker container argument — privileged=true. Moreover, a volume maps to the container’s path /sys/fs/cgroup is also necessary.

Here is a Dockerfile code:

FROM centos7-image
ENV container docker
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ $i == \
systemd-tmpfiles-setup.service ] || rm -f $i; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*;\
rm -f /etc/systemd/system/*.wants/*;\
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*;\
rm -f /lib/systemd/system/anaconda.target.wants/*;
VOLUME [ "/sys/fs/cgroup" ]
RUN yum clean all && \
yum -y install openssh-server openssh-clients initscripts
RUN ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
RUN ssh-keygen -f /etc/ssh/ssh_host_ed25519_key -N '' -t ed25519
EXPOSE 22
# setup new root password
RUN echo root:pass | chpasswd
CMD ["/usr/sbin/init"]

To mount the volume /sys/fs/cgroup on Windows, we need to leverage WSL backend because it’s a real Linux environment. What we need to do is create the same folder on Linux subsystem inside Windows.

sudo mkdir /sys/fs/cgroup/systemd
sudo mount -t cgroup -o none,name=systemd cgroup /sys/fs/cgroup/systemd

This can also help enable systemctl command on your docker container. Otherwise, you may receive an error message like ‘Failed to get D-Bus connection: Operation not permitted’ while running systemctl command inside the docker container

References

https://gist.github.com/ederparaiso/4847aa4e117f2d1e35d14259e6ef8b2d

https://github.com/microsoft/wsl/issues/4189

--

--

Tony Qu
Tony Qu

Written by Tony Qu

.NET Veteran, Project Manager, Maintainer of NPOI, Senior Researcher for MSFT related affairs

No responses yet