使用ssh连接code-server容器

最近经常要带平板出去,就用docker拉了个code-server镜像方便在平板上开发,但是我想平时在电脑上写完代码后能在平板上接着写,于是就研究了一下如何在vscode上连上code-server容器

如果你觉得配置环境很浪费时间,这里有我打包好的镜像

环境准备

首先使用docker pull codercom/code-server拉取镜像

我的启动命令

1
2
3
4
5
6
7
8
docker run \
--name=my_code-server \
-e PASSWORD=123 \
-e DEFAULT_WORKSPACE=/home/code \
-p 1472:8080 \
-p 1473:22 \
-v /home/code:/home/code \
--restart=always --privileged=true -d codercom/code-server:latest

开始!

修改root密码和apt源

为了方便,我在vscode中打算使用root身份登录容器,所以需要修改root的密码sudo passwd root

为了接下来更方便,推荐修改apt源为镜像源nano /etc/apt/sources.list(可以使用cat /etc/issue确定系统版本)

清华镜像源

以debian 12为例

我这里是debian 12:

1
2
3
4
5
6
7
8
9
10
11
12
# 默认注释了源码镜像以提高 apt update 速度,如有需要可自行取消注释
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware

deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware

deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware

deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware
# deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware

安装配置ssh服务端

然后更新并安装ssh服务端apt update&&apt upgrade&&apt install openssh-server

如果使用root账户密码登录,就要修改/etc/ssh/sshd_config文件(把#PermitRootLogin prohibit-password改为PermitRootLogin yes)

然后运行sshd服务:mkdir -p /var/run/sshd, /usr/sbin/sshd -D &

检查是否正在运行ps -e | grep sshd

如果有进程显示,说明sshd服务已经启动

使用ssh密钥

但是,每次连接都需要输入账号密码,很麻烦,可以使用ssh密钥登录

如果是第一次使用,需要生成密钥对

觉得我写的太简单可以参考菜鸟教程

首先在你的客户端(注意是客户端!)运行ssh-keygen

然后找到生成的公钥(.pub)(Windows默认路径是C:\Users\<用户名>\.ssh\id_rsa.pub),复制到容器的/root/.ssh/authorized_keys文件中

vscode配置

在vscode中安装Remote - SSH插件,然后F1输入Remote-SSH: Open Configuration File...打开配置文件,添加如下内容

1
2
3
4
Host <名字,可以随便取>
HostName <你的服务器ip或者域名>
Port 1473(端口,这里我设置的是1473)
User root(用户,root)

简化方法-使用我打包的镜像

由于我觉得每次都要手动配置好麻烦,就基于code-server打包了一个镜像(seeker472/code-server-toolpack)如果你觉得上面的操作太麻烦,可以直接使用我打包好的镜像

这个镜像相比官方镜像:

  • 默认安装了 gcc gdb g++ git openjdk python3 nodejs npm 等常用软件
  • 已经配置好了ssh服务端
  • 已经把源修改成了清华大学镜像站
  • 修改了product.json,让拓展商店使用vscode默认的商店

配置方法大同小异:

1
2
3
4
5
6
7
8
docker run \
--name=my_code-server \
-e PASSWORD=123 \
-e DEFAULT_WORKSPACE=/home/code \
-p 1472:8080 \
-p 1473:22 \
-v /home/code:/home/code \
--restart=always --privileged=true -d seeker472/code-server-toolpack

当然,你依旧需要手动修改Root密码配置ssh密钥


使用ssh连接code-server容器
https://20040702.xyz/2024/03/03/old/codeserver-ssh/
作者
Seeker
发布于
2024年3月3日
许可协议