docker中无法使用systemctl

Ubuntu docker中无法使用systemctl

当我在系统为Ubuntu18.04的服务器上尝试pull一个ubuntu或者debian的容器并运行的时候,在容器中尝试使用 systemctl命令,结果出现了System has not been booted with systemd as init system (PID 1). Can’t operat的报错,意思是init的进程号为1的进程(其实init根本没运行)。 对于centos镜像,我们可以在启动容器的时候设置第一条命令为 docker run -tid --name centos01 --privileged=true centos8 /usr/sbin/init,之前网上有提到对于debian/ubuntu可以使用docker run -tid --name ubuntu01 --privileged=true ubuntu:18.04 /sbin/init的命令来启动,不过实测,当前版本的镜像已经不行了,会出现docker: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused “exec: \"/sbin/init\”: stat /sbin/init: no such file or directory": unknown的报错,因为新的debian和ubuntu镜像中移除了init软件包,如果我们还想在debian/ubuntu的docker容器中使用systemctl命令,我们需要修改官方镜像。 创建一个Dockerfile:

nano Dockerfile
#填入以下内容并保存
FROM ubuntu:18.04
RUN apt-get update && apt-get install -y init && apt-get clean all
#另外我还希望创建的镜像能够安装ssh并允许密码登录
RUN apt-get update && apt-get install -y openssh-server nano lsof
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN /usr/sbin/sshd -D &
EXPOSE 22
#构建镜像
docker build -f ./Dockerfile . -t aoyouer/ubuntu
#启动容器
docker run -tid --name ub -p 2222:22 --privileged=true aoyouer/ubuntu /sbin/init

之后发现在容器中可以使用systemctl了,并且可以直接使用ssh服务了。

参考

https://juejin.im/post/5d4007a3f265da03e5230fc6 https://docs.docker.com/engine/examples/running_ssh_service/ http://www.hxstrive.com/article/651.htm

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
本站访客数:
Built with Hugo
主题 StackJimmy 设计