Golang Playground 是 Golang 的代码在线运行服务,官方地址为:https://play.golang.org。但是由于国内网络原因,此地址无法访问。因此,考虑自行搭建此服务,供自己使用。本文主要记录搭建过程,基于的 Golang 版本为 1.16。

搭建步骤

下载代码,Gitee 地址为:https://gitee.com/MACDfree/playground,此仓库已针对国内环境进行了修改。

1
git clone https://gitee.com/MACDfree/playground.git

构建 golang/playground 镜像

1
docker build --network=host -t golang/playground .

构建 golang/play-sandbox 镜像

1
 docker build --network=host -t golang/playground-sandbox -f sandbox/Dockerfile .

构建 golang/playground-sandbox-gvisor 镜像

1
docker build --network=host -f sandbox/Dockerfile.gvisor -t golang/playground-sandbox-gvisor .

下载 runsc,地址为:https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc。设置可执行权限并移动到 /usr/local/bin 目录下。最后修改 docker 配置文件并重启。

1
2
3
4
chmod +x runsc
cp runsc /usr/local/bin/
vim /etc/docker/daemon.json
systemctl restart docker

daemon.json 内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
    "registry-mirrors": [
        "https://docker.mirrors.ustc.edu.cn/",
        "https://registry.docker-cn.com"
    ],
    "runtimes": {
        "runsc": {
            "path": "/usr/local/bin/runsc"
        }
    }
}

启动容器

1
2
3
docker run --name=sandbox_dev -d -p 80:80/tcp -v /var/run/docker.sock:/var/run/docker.sock golang/playground-sandbox --dev -untrusted-container=golang/playground-sandbox-gvisor:latest
docker run --name=play -d --rm -e SANDBOX_BACKEND_URL="http://192.168.57.10/run" -p 8080:8080 golang/playground
docker run --name=playnew -d --rm -e APP_PLAYGROUND_URL="http://192.168.57.10:8080" -p 8000:8000 x1unix/go-playground

由于一个 playground 应用需要涉及 3 个容器,所以使用 docker-compose 简化了启动操作。只要使用 docker-compose up -ddocker-compose down 两个命令进行应用的启动和停止。docker-compose.yml 内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
version: "3"
services:
  playground:
    image: x1unix/go-playground:latest
    networks:
      - innernet
    environment:
      APP_PLAYGROUND_URL: "http://innernet.playground:8080"
    depends_on:
      - playground_inner
    ports:
      - "8000:8000"
  playground_inner:
    image: golang/playground:latest
    networks:
      innernet:
        aliases:
          - innernet.playground
    environment:
      SANDBOX_BACKEND_URL: "http://innernet.sandbox/run"
      PLAY_GOPROXY: "https://goproxy.cn"
    depends_on:
      - playground-sandbox
    ports:
      - "8080:8080"
  playground-sandbox:
    image: golang/playground-sandbox:latest
    networks:
      innernet:
        aliases:
          - innernet.sandbox
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command:
      - "--dev"
      - "-untrusted-container=golang/playground-sandbox-gvisor:latest"
    expose:
      - "80"
networks:
  innernet: