[DOCKER] Build a Go development environment with VS Code's Remote Containers

Introduction

It was comfortable to build a Go development environment using Remote Containers, which is an extension of VS Code, so I will introduce it. I will omit the installation method of VS Code and Docker Desktop.

Remote Containers Remote Containers is an extension of VS Code's remote development features that is specialized for Docker. In addition, it seems that there are "Remote SSH" that connects remotely via SSH and "Remote WSL" that connects remotely using WSL (Windows Subsystem for Linux).

By connecting remotely from the local VS Code to the Docker container via VS Code Server, it is possible to develop in an environment separate from the local environment. In other words, it's a great feature that doesn't pollute the local environment while benefiting from code completion, etc., because everything is done on Docker.

Installation

Find and install Remote Containers from VS Code Extensions. image.png

Initial setting

Open the menu with Ctrl + Shift + P and Select Remote-Containers: Add Development Cotainers Configuration Files .... image.png

In my environment, I have already built the environment with docker-compose.yml and DockerFile, so I can make the initial settings based on those settings. You can also use the preset settings by selecting From a predefined container configuration definition .... This time, we will use the existing docker-compose file for initial setup. image.png

image.png

.devcontainer When you make the initial settings, the .devcontainer folder is automatically created and under it. ・ Devcontainer.jsonDocker-compose.yml Is automatically generated. devcontainer.json will be the configuration file.

Here, the current directory structure is as follows.

- .devcontainer
 ├ devcontainer.json
  └ docker-compose.yml
- sample
└ Source code
- docker-compose.yml
- docker-compose.dev.yml
- Dockerfile 
- Dockerfile.dev

The automatically generated files are as follows.

devcontainer.json


// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.
{
	"name": "Existing Docker Compose (Extend)",

	// Update the 'dockerComposeFile' list if you have more compose files or use different names.
	// The .devcontainer/docker-compose.yml file contains any overrides you need/want to make.
	"dockerComposeFile": [
		"..\\docker-compose.dev.yml",
		"docker-compose.yml"
	],

	// The 'service' property is the name of the service for the container that VS Code should
	// use. Update this value and .devcontainer/docker-compose.yml to the real service name.
	"service": "sample",

	// The optional 'workspaceFolder' property is the path VS Code should open by default when
	// connected. This is typically a file mount in .devcontainer/docker-compose.yml
	"workspaceFolder": "/workspace",

	// Set *default* container specific settings.json values on container create.
	"settings": {
		"terminal.integrated.shell.linux": null
	},

	// Add the IDs of extensions you want installed when the container is created.
	"extensions": []

	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	// "forwardPorts": [],

	// Uncomment the next line if you want start specific services in your Docker Compose config.
	// "runServices": [],

	// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
	// "shutdownAction": "none",

	// Uncomment the next line to run commands after the container is created - for example installing curl.
	// "postCreateCommand": "apt-get update && apt-get install -y curl",

	// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
	// "remoteUser": "vscode"
}

docker-compose.yml


version: '3'
services:
  # Update this to the name of the service you want to work with in your docker-compose.yml file
  sample:
    # If you want add a non-root user to your Dockerfile, you can use the "remoteUser"
    # property in devcontainer.json to cause VS Code its sub-processes (terminals, tasks, 
    # debugging) to execute as the user. Uncomment the next line if you want the entire 
    # container to run as this user instead. Note that, on Linux, you may need to 
    # ensure the UID and GID of the container user you create matches your local user. 
    # See https://aka.ms/vscode-remote/containers/non-root for details.
    #
    # user: vscode

    # Uncomment if you want to override the service's Dockerfile to one in the .devcontainer 
    # folder. Note that the path of the Dockerfile and context is relative to the *primary* 
    # docker-compose.yml file (the first in the devcontainer.json "dockerComposeFile"
    # array). The sample below assumes your primary file is in the root of your project.
    #
    # build:
    #   context: .
    #   dockerfile: .devcontainer/Dockerfile
    
    volumes:
      # Update this to wherever you want VS Code to mount the folder of your project
      - .:/workspace:cached

      # Uncomment the next line to use Docker from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker-compose for details.
      # - /var/run/docker.sock:/var/run/docker.sock 

    # Uncomment the next four lines if you will use a ptrace-based debugger like C++, Go, and Rust.
    # cap_add:
    #   - SYS_PTRACE
    # security_opt:
    #   - seccomp:unconfined

    # Overrides default command so things don't shut down after the process ends.
    command: /bin/sh -c "while sleep 1000; do :; done"

Settings for Go

We will add settings for developing Go.

extensions Locally installed VS Code extensions are not available inside the remote container, so set the extensions to be installed automatically when the container starts. Put in Go extensions. This string can be obtained from the right-click Copy Extension Id in the extension list.

devcontainer.json


	"extensions": [
		"golang.go"
	]

settings Since gopls is used, add the settings by referring to github. Regarding Gomod setting (GO111MODULE), it is no longer necessary after 1.13, but if you do not set it, an error will appear in the import statement, so set it.

devcontainer.json


"settings": {
		"terminal.integrated.shell.linux": "/bin/bash",
		"go.useLanguageServer": true,
		"[go]": {
			"editor.formatOnSave": true,
			"editor.codeActionsOnSave": {
				"source.organizeImports": true,
			},
			// Optional: Disable snippets, as they conflict with completion ranking.
			"editor.snippetSuggestions": "none",
		},
		"[go.mod]": {
			"editor.formatOnSave": true,
			"editor.codeActionsOnSave": {
				"source.organizeImports": true,
			},
		},
		"gopls": {
			// Add parameter placeholders when completing a function.
			"usePlaceholders": true,
			// If true, enable additional analyses with staticcheck.
			// Warning: This will significantly increase memory usage.
			"staticcheck": false,
		},
		"go.toolsEnvVars":{
			"GO111MODULE":"on"
		}
	}

workspaceFolder Set the workspace when starting the remote container. On the docker-compose.yml side, the volume will be mounted under / go / src /, so change the workspace accordingly.

devcontainer.json


"workspaceFolder": "/go/src/sample",

Setup is completed.

Start-up

Actually start the container. Select Remote-Containers: Reopen in Container from Ctrl + Shift + P

image.png

At the first startup, the tools are not installed in / go / bin, so install them.

Since gopls is used, install it from the notification below, or Run go get -v golang.org/x/tools/gopls image.png

For other tools, install other than gocode and gocode-gomod from Go: Install / Update Tools. image.png

image.png

I was able to confirm that everything was installed under / go / bin.

image.png

At this point, you can develop on the container. Of course, it is managed on a container-by-container basis, so if you delete a container, the installed one will disappear, so you will need to reconfigure it.

debug

You can also debug inside the container. Create a .vscode folder in the same directory as the mounted source code and create a launch.json.

launch.json


{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Remote",
            "type": "go",
            "request": "launch",
            "host": "localhost",
            "program": "${workspaceRoot}",
            "args": []
        }
    ]
}

Summary

I will describe the file that was finally created. I hope you find it helpful.

devcontianer.json


{
	"name": "Existing Docker Compose (Extend)",
	"dockerComposeFile": [
		"docker-compose.yml"
	],
	"service": "sample",
	"workspaceFolder": "/go/src/sample",
	"settings": {
		"terminal.integrated.shell.linux": "/bin/bash",
		"go.useLanguageServer": true,
		"[go]": {
			"editor.formatOnSave": true,
			"editor.codeActionsOnSave": {
				"source.organizeImports": true,
			},
			"editor.snippetSuggestions": "none",
		},
		"[go.mod]": {
			"editor.formatOnSave": true,
			"editor.codeActionsOnSave": {
				"source.organizeImports": true,
			},
		},
		"gopls": {
			"usePlaceholders": true,
			"staticcheck": false,
		},
		"go.toolsEnvVars":{
			"GO111MODULE":"on"
		}
	},
	"extensions": [
		"golang.go"
	]
}

docker-compose.yml


version: '3'
services:
  # Update this to the name of the service you want to work with in your docker-compose.yml file
  sample:
    image: golang:1.14
    volumes:
      - ./../:/go/src/:cached
    tty: true
    environment:
      - MYSQL_CONNECTION_STRING=${CONNECTION_STRING}
    networks:
      - default
      - db-network
networks:
  db-network:
    external: true

reference

--Go study (1) Mac + VSCode + Go environment setting: https://qiita.com/oruharo/items/545378eae5c707f717ed

Recommended Posts

Build a Go development environment with VS Code's Remote Containers
Build a comfortable development environment with VSCode x Remote Development x Pipenv
Easily build a development environment with Laragon
[Django] Use VS Code + Remote Containers to quickly build a Django container (Docker) development environment.
Build a C language development environment with a container
Go (Echo) Go Modules × Build development environment with Docker
[Python] Build a Django development environment with Docker
Build a Django development environment with Doker Toolbox
Build a python execution environment with VS Code
Build a machine learning application development environment with Python
Build a development environment with Poetry Django Docker Pycharm
Cross-compiling Raspberry Pi and building a remote debugging development environment with VS Code
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)
[Memo] Build a development environment for Django + Nuxt.js with Docker
Build a go environment using Docker
Create a GO development environment with [Mac OS Big Sur]
[Django] Build a Django container (Docker) development environment quickly with PyCharm
How to build a python2.7 series development environment with Vagrant
Build a Python environment with WSL + Pyenv + Jupyter + VS Code
[No venv required] The strongest Python development environment created with Remote Containers [VS Code / Docker]
Create a development environment for Go + MySQL + nginx with Docker (docker-compose)
Create a simple Python development environment with VS Code and Docker
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
Build a Tensorflow environment with Raspberry Pi [2020]
Build a Fast API environment with docker-compose
[Linux] Build a jenkins environment with Docker
Build a python virtual environment with pyenv
Build a modern Python environment with Neovim
[Linux] Build a Docker environment with Amazon Linux 2
I tried to build a Mac Python development environment with pythonz + direnv
Environment construction with VSCode + Remote Container (Go / Application)
Build a WardPress environment on AWS with pulumi
Build Django + NGINX + PostgreSQL development environment with Docker
Build the fastest Django development environment with docker-compose
Build Python development environment with Visual Studio Code
Build a python environment with ansible on centos6
Create a python3 build environment with Sublime Text3
Build a development environment using Jupyter and Flask with Python in Docker (supports both VS Code / code-server)
Build a Django environment with Vagrant in 5 minutes
Build a Python development environment on your Mac
[Memo] Build a virtual environment with Pyenv + anaconda
Build a virtual environment with pyenv and venv
Build a Kubernetes environment for development on Ubuntu
Build a Python environment with OSX El capitan
Build a Minecraft plugin development environment in Eclipse
Quickly build a Python Django environment with IntelliJ
Build a mruby development environment for ESP32 (Linux)
Build a Python machine learning environment with a container
Build a Python development environment on Raspberry Pi
Get a quick Python development environment with Poetry
[January 2020] Let's start the explosive "development container" with VS Code's Remote Container in earnest.
Build a TensorFlow development environment on Amazon EC2 with command copy and paste
Build a local development environment with WSL + Docker Desktop for Windows + docker-lambda + Python
Build a GVim-based Python development environment on Windows 10 (3) GVim8.0 & Python3.6
Build a Django development environment using pyenv-virtualenv on Mac
Build a python virtual environment with virtualenv and virtualenvwrapper
Build a local development environment for Laravel6.X on Mac
Repairing a broken development environment with mavericks migration (Note)
Build a python environment for each directory with pyenv-virtualenv
Create a python development environment with vagrant + ansible + fabric
Build a GVim-based Python development environment on Windows 10 (1) Installation