k8s部署应用多容器的sshd

创建eg_sshd镜像

准备Dockerfile文件

以下内容Dockerfile在容器中设置了sshd服务,您可以使用ssh连接到该容器中。

  • 使用RUN echo 'root:123456' | chpasswd,将“ 123456”替换为之前生成的密码。
  • 使用RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_configwithout-password代替prohibit-passwordUbuntu 14.04。
FROM ubuntu:16.04

RUN apt-get update && apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:THEPASSWORDYOUCREATED' | 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

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

使用以下方法生成image

$ docker build -t eg_sshd .

运行一个test_sshd容器

$ docker run -d -P --name test_sshd eg_sshd
$ docker port test_sshd 22

0.0.0.0:32768

现在,您可以ssh宿主机的IP+端口访问到容器内部:

$ ssh root@192.168.1.2 -p 49154
# or
$ ssh root@localhost -p 49154
# The password is ``123456``.
root@f38c87f2a42d:/#

推送镜像到docker私库

$ docker build -t ${image_name}:${image_version}
$ docker login ${your_docker_repositry}
$ docker push ${image_name}:${image_version}

清理本地文件

$ docker container stop test_sshd
$ docker container rm test_sshd
$ docker image rm eg_sshd

创建deployment

以下为ssh_deployment内容,使用NodePort对集群外部暴露service端口,以便集群外可以通过该端口访问到容器内的sshd服务。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sshd
  labels:
    app: sshd
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: sshd
  template:
    metadata:
      labels:
        app: sshd
    spec:
      containers:
        - name: sshd-server
          image: ××××××/library/eg_sshd_ubuntu:v1.0
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 22
---
apiVersion: v1
kind: Service
metadata:
  name: sshd
  namespace: default
spec:
  type: NodePort
  ports:
    - port: 22
      targetPort: 22
      nodePort: 32722
  selector:
    app: sshd

运行deployment

$ kubectl apply -f ssh_deployment.yaml

# get all resource in k8s
$ kubectl get all --all-namespaces

外部访问sshd服务

$ ssh root@${k8s_ip} -p 32722
root@k8s_ip's password: 
Welcome to Ubuntu 16.04.6 LTS (GNU/Linux 3.10.0-693.el7.x86_64 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

root@sshd-58c69bd58c-4b8sb:~# 

清理集群

$ kubectl delete -f ssh_deployment.yaml

参考

Dockerize an SSH service

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐