Connect docker container through browser

mokeyWie 2020-11-11 11:47:15
connect docker container browser


Use within the company Jenkins do CI/CD when , There are often cases of project construction failure , In general, through Jenkins The output of the build console can be used to understand the possible problems , But there are special cases where development needs to be done in Jenkins Troubleshooting on the server , At this time, we can only find operation and maintenance to debug , For the experience of developers, I investigated web terminal, Can provide the container terminal to the development for troubleshooting when the build fails .

Effect display

Support color highlight , Support tab Key completion , Support copy and paste , The experience is basically the same as the ordinary terminal Agreement .

be based on docker Of web terminal Realization

docker exec call

The first thing I think about is through docker exec -it ubuntu /bin/bash Command to open a terminal , Then the standard input and output are passed through websocket Interact with the front end .

And found that docker offer API and SDK developable , adopt Go SDK Can be very convenient in docker Create a terminal process in :

  • install sdk
go get -u[email protected]

This project is new tag Not followed go mod server semantics , So if you just go get -u The default installation is 2017 One of the years tag edition , I'm directly here master I found one on the branch commit ID, Specific reason reference issue

  • call exec
package main
import (
func main() {
// initialization go sdk
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
// Execute in the specified container /bin/bash command
ir, err := cli.ContainerExecCreate(ctx, "test", types.ExecConfig{
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Cmd: []string{"/bin/bash"},
Tty: true,
if err != nil {
// Attach to the created above /bin/bash In progress
hr, err := cli.ContainerExecAttach(ctx, ir.ID, types.ExecStartCheck{Detach: false, Tty: true})
if err != nil {
// close I/O
defer hr.Close()
// Input
// Output
scanner := bufio.NewScanner(hr.Conn)
for scanner.Scan() {

This is the time docker The input and output of the terminal are available , The next step is through websocket To interact with the front end .

Front page

When we're in linux terminal Knock up and down ls On command , To see is :

[email protected]:/# ls
bin dev home lib64 mnt proc run srv tmp var
boot etc lib media opt root sbin sys usr

In fact, the string returned from standard output is :

[0m[01;34mbin[0m [01;34mdev[0m [01;34mhome[0m [01;34mlib64[0m [01;34mmnt[0m [01;34mproc[0m [01;34mrun[0m [01;34msrv[0m [30;42mtmp[0m [01;34mvar[0m
[01;34mboot[0m [01;34metc[0m [01;34mlib[0m [01;34mmedia[0m [01;34mopt[0m [01;34mroot[0m [01;34msbin[0m [01;34msys[0m [01;34musr[0m

In this case , There's already one called xterm.js The library of , Designed to simulate Terminal Of , We need to do terminal display through this library .

var term = new Terminal();"terminal"));
term.write("Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ");

Through official examples , You can see that it will display special characters accordingly :

In this case, you just need to be in websocket When you connect to the server , Use... To get the terminal output term.write() Write out , Then the front-end input as the input of the terminal can achieve the function we need .

The idea is right , But there's no need to write ,xterm.js One has been provided websocket Plug ins are here to do this , We just need to pass the standard input and output through websocket Transmission is OK .

  • install xterm.js
npm install xterm
  • be based on vue Write the front page
<div ref="terminal"></div>
// introduce css
import "xterm/dist/xterm.css";
import "xterm/dist/addons/fullscreen/fullscreen.css";
import { Terminal } from "xterm";
// Adaptive plug-ins
import * as fit from "xterm/lib/addons/fit/fit";
// Full screen plug-in
import * as fullscreen from "xterm/lib/addons/fullscreen/fullscreen";
// web Link plugin
import * as webLinks from "xterm/lib/addons/webLinks/webLinks";
// websocket plug-in unit
import * as attach from "xterm/lib/addons/attach/attach";
export default {
name: "Index",
created() {
// Installing a plug-in
// Initialize the terminal
const terminal = new Terminal();
// open websocket
const ws = new WebSocket("ws://");
// Bound to the dom On$refs.terminal);
// Add plug-ins;

Back end websocket Support

stay go Is not provided in the standard library of websocket Modular , Here we use the official order websocket library .

go get -u

The core code is as follows :

// websocket Handshake configuration , Ignore Origin testing
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
func terminal(w http.ResponseWriter, r *http.Request) {
// websocket handshake
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
defer conn.Close()
// Get the container ID or name
container := r.Form.Get("container")
// perform exec, Get the connection to the container terminal
hr, err := exec(container)
if err != nil {
// close I/O flow
defer hr.Close()
// Withdraw from the process
defer func() {
// Forward input / Output to websocket
go func() {
wsWriterCopy(hr.Conn, conn)
wsReaderCopy(conn, hr.Conn)
func exec(container string) (hr types.HijackedResponse, err error) {
// perform /bin/bash command
ir, err := cli.ContainerExecCreate(ctx, container, types.ExecConfig{
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Cmd: []string{"/bin/bash"},
Tty: true,
if err != nil {
// Attach to the created above /bin/bash In progress
hr, err = cli.ContainerExecAttach(ctx, ir.ID, types.ExecStartCheck{Detach: false, Tty: true})
if err != nil {
// Forward the output of the terminal to the front end
func wsWriterCopy(reader io.Reader, writer *websocket.Conn) {
buf := make([]byte, 8192)
for {
nr, err := reader.Read(buf)
if nr > 0 {
err := writer.WriteMessage(websocket.BinaryMessage, buf[0:nr])
if err != nil {
if err != nil {
// Forward the input from the front end to the terminal
func wsReaderCopy(reader *websocket.Conn, writer io.Writer) {
for {
messageType, p, err := reader.ReadMessage()
if err != nil {
if messageType == websocket.TextMessage {


The above is a simple docker web terminal function , After that, you just need to pass it through the front end container ID or container name You can open the specified container for interaction .

Complete code :

I am a MonkeyWie, Welcome to scan ! To share in public official account JAVAGolang front end dockerk8s Knowledge of dry goods .



  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云