将本地部署Visual Studio Code Server作为服务

发布于 2022-12-03  326 次阅读


继第三方开发的可用于浏览器的VSCode版本code-server之后,微软官方也推出了可以自行托管的版本。目前微软的版本有使用微软的中转服务器,以及监听本地端口两种模式,但使用中转的模式目前需要收到邀请的账号才能使用,所以这次使用本地模式。需要注意的是本地模式安全性不高,如果需要在公网中使用建议添加HTTPS或者使用隧道来确保安全。这里简单介绍一下如何将Linux版作为系统服务来自动运行。

更新:目前该功能已经正式上线并内置在VSCode中,无需收到邀请即可使用隧道中转。本地监听模式目前在预览版中可用,且命令从serve-local变为serve-web

首先按照文档进行安装:

Linux:

wget -O- https://aka.ms/install-vscode-server/setup.sh | sh

Windows x64:

New-Item "${HOME}\.vscode-server-launcher\bin" -Force -ItemType "directory"
Invoke-WebRequest "https://aka.ms/vscode-server-launcher/x86_64-pc-windows-msvc" -OutFile "${HOME}\.vscode-server-launcher\bin\code-server.exe"
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";${HOME}\.vscode-server-launcher\bin", "User")

Windows ARM:

New-Item "${HOME}\.vscode-server-launcher\bin" -Force -ItemType "directory"
Invoke-WebRequest "https://aka.ms/vscode-server-launcher/aarch64-pc-windows-msvc" -OutFile "${HOME}\.vscode-server-launcher\bin\code-server.exe"
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";${HOME}\.vscode-server-launcher\bin", "User")

可以不用管理员权限安装Windows版,但是安装后可能需要重启终端来刷新环境变量。

然后执行命令启动:

code-server serve-local --accept-server-license-terms --host 0.0.0.0

其中--accept-server-license-terms为接受许可协议,如果不添加该参数则启动时会询问是否接受,--host 0.0.0.0为监听的IP地址,如果需要从其他设备访问需要添加此参数并打开防火墙端口,未设置的话默认监听localhost的8080端口。测试成功启动后使用Ctrl+C退出即可。

在/etc/systemd/system下创建code-server.service文件:

[Unit]
Description=VSCode Remote Server

[Service]
User={Your Username}
Group={Your Group}

ExecStart=/usr/local/bin/code-server serve-local --accept-server-license-terms --host 0.0.0.0

[Install]
WantedBy=default.target

其中的{Your Username}和{Your Group}改为需要执行命令的用户和用户组,如果想修改端口也可以添加--port参数。

完成后启用服务即可:

sudo systemctl enable --now code-server

访问所需的包含令牌的链接可以通过查看日志获得:

journalctl -u code-server
届ける言葉を今は育ててる
最后更新于 2022-12-03