思科DevNet

Docker:Pycharm 通过 ssh 远程连接 Docke

2020-10-23  本文已影响0人  dex0423

1. 在 Docker 上搭建 CentOS

这是前置步骤,详细步骤请参考我的另一篇文章 《Docker:基于 CentOS 搭建 python3.8 开发环境并保存镜像》。

2. 设置 CentOS 登陆密码

yum install passwd -y

修改密码

passwd
[root@ad8750c26f60 /]# passwd
Changing password for user root.
New password:
/usr/share/cracklib/pw_dict.pwd.gz: No such file or directory
BAD PASSWORD: The password fails the dictionary check - error loading dictionary
Retype new password:
passwd: all authentication tokens updated successfully.

3. 安装 ssh

yum install openssh-server -y

4. 配置 ssh

生成 ssh 容器的公钥、私钥

cd /etc/ssh
ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
ssh-keygen -t rsa -f /etc/ssh/ssh_host_ecdsa_key
ssh-keygen -t rsa -f /etc/ssh/ssh_host_ed25519_key

注意:生成过程中需要两次回车,以进行下一步。

创建允许外部访问的认证文件

mkdir -p ~/.ssh
> ~/.ssh/authorized_keys

编写容器的服务启动脚本

vi /run.sh

写入如下内容后保存退出

#!/bin/bash
/usr/sbin/sshd -D

设置执行权限

chmod +x /run.sh

5. 退出容器,保存镜像

退出容器

exit

查看镜像 CONTAINER ID,我这里为 ad8750c26f60

docker ps -a

commit 为新的镜像

docker commit ad8750c26f60 centos-python3.8-ssh

查看新镜像

C:\Users\zgd>docker images
REPOSITORY             TAG                 IMAGE ID            CREATED             SIZE
centos-python3.8-ssh   latest              177e633461ea        7 seconds ago       986MB
centos-python3.8       latest              ff48920deabb        52 minutes ago      947MB
centos                 latest              0d120b6ccaa8        2 months ago        215MB

6. 启动并通过 ssh 连接新容器

docker run -d --name centos7_ssh -p 2222:22 centos-python3.8-ssh /run.sh

参数说明:

本地 ssh 连接容器

ssh root@127.0.0.1 -p 2222

连接成功

C:\Users\zgd>ssh root@127.0.0.1 -p 2222
The authenticity of host '[127.0.0.1]:2222 ([127.0.0.1]:2222)' can't be established.
RSA key fingerprint is SHA256:VOyhux1cjQd+AJKxNCKuitzv0jVrO4pAljeRjtP2LYg.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added '[127.0.0.1]:2222' (RSA) to the list of known hosts.
root@127.0.0.1's password:
"System is booting up. Unprivileged users are not permitted to log in yet. Please come back later. For technical details, see pam_nologin(8)."
"System is booting up. Unprivileged users are not permitted to log in yet. Please come back later. For technical details, see pam_nologin(8)."
[root@e9843dab0074 ~]#

7. 获取 host ip

ipconfig

注意:

  • 通过这里获取到的 ip,局域网内的其他机器可以自由的访问容器环境;
  • 如果 pycharm 运行的主机和 docker 运行的主机是 同一台机器,那么 host ip 就是 127.0.0.1

8. Pycharm ssh 连接容器 python

打开 pycharm,依次点击 File > Settings > Project > Python Interpreter

image.png

依次点击 Show All > + > SSH Interpreter,依次输入 host ip、2222、root,点击 Next

image.png
输入前面设置的密码,点击 Next

编译器路径选择 /usr/local/bin/python3.8

image.png

pycharm 底部的任务栏出现如下内容,表示配置成功,当前项目文件已被上传到 CentOS 容器的 tem 文件夹下;


image.png

配置结束。

上一篇下一篇

猜你喜欢

热点阅读