VScode遠程連接Docker容器實現X11轉發


需求

一般在Windows做Linux下C++開發都會用虛擬機解決,進階一點可能會想到VScode remote + WSL
這些方案終究沒有擺脫性能限制,對於龐大工程本地編譯動輒十分鍾以上的make嚴重影響體驗
希望利用遠程高性能Linux服務器的多核心與大內存加速開發
同時調試用到OpenCV的imshow需要打通Docker容器的X11轉發

准備

Windows

Windows這邊需要安裝X11程序,常見商業軟件Xmanager,免費的XMing和VcXsrv這里選擇微軟的開源VcXsrv
https://sourceforge.net/projects/vcxsrv/
安裝后進行簡單配置,保留默認Multiple windows和Display number -1

第二步選start no client

這一步比較重要,勾選Disable acccess control

完成配置可在右下角托盤內看到服務已經啟動

打開VScode安裝Remote-SSH插件

在PowerShell內使用ssh-keygen生成公鑰(一路回車)
復制~/.ssh/id_rsa.pub內容

Linux

下載安裝docker並將當前用戶加入docker組

sudo apt install docker.io
sudo usermod -aG docker $USER

替換國內服務器加速下載

sudo vim /etc/docker/daemon.json
# Add following content
{"registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]}

重啟Docker服務生效

sudo service docker restart

拉取基礎鏡像(以Ubuntu 18.04為例)

docker pull ubuntu:18.04

啟動容器並打開端口映射

docker run -it -p 8022:22 --name remote ubuntu:18.04 bash

若需要在Docker使用gdb調試還需增加參數--security-opt seccomp=unconfined否則報錯ptrace:Operation not permitted

docker run -it -p 8022:22 --name remote --security-opt seccomp=unconfined ubuntu:18.04 bash

更換apt源並安裝常用工具(至少安裝openssh-server)

sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
apt update
apt install -y vim git openssh-server cmake autoconf build-essential libopencv-dev

確保/etc/ssh/sshd_config中已配置X11Forwarding yes
啟動ssh服務端

/etc/init.d/ssh start

默認不允許root用戶使用密碼連接,需要創建公鑰認證文件

cd
mkdir .ssh
chmod 700 .ssh
cd .ssh
vi authorized_keys
# paste content from Windows id_rsa.pub and save
chmod 600 authorized_keys

准備就緒,按下Ctrl+PQ斷開容器連接

連接

點擊VScode左側Remote選擇添加,輸入容器所在宿主機ip與映射端口號ssh root@10.0.1.97 -p 8022

選擇默認ssh配置文件C:/Users/XXX/.ssh/config進行更新
點擊右下角Connect進行連接

等待VScod自動下載安裝code-server完成,最后在容器終端內配置X11轉發地址(修改10.0.1.51為Windows內網ip)

export DISPLAY=10.0.1.51:0.0

測試

在VScode內置terminal中安裝xeyes

apt install x11-apps
xeyes

X11轉發正常

參考

如何在Docker內部使用gdb調試器 - 簡書


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM