Setting Up a Go Development Environment Using Dev Containers
Greetings, dev! I’m Chris, a software engineer hailing from Plymouth, UK.
For my opening blog entry, I’m keeping it concise and straightforward, diving into the setup of a development environment in Go with the use of dev containers.
Assuming you’ve already equipped your operating system with vscode
and Docker
, we can proceed. If not, it might be a good time to do so!
Start by installing the Remote Containers extension. You can secure it here.
With that set, create a Dockerfile
with the following code:
FROM golang:1.20.4-buster
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \\
&& apt-get -y install --no-install-recommends apt-utils 2>&1 \\
&& useradd -s /bin/bash -m chris
RUN apt-get -y install git
RUN chown -R chris:chris /go
USER chris
ENV DEBIAN_FRONTEND=dialog
EXPOSE 8000
This file primarily fetches golang:1.20.4 and establishes a Debian Linux distribution for our development environment. The inclusion of ENV DEBIAN_FRONTEND=noninteractive
ensures terminal interactions remain nonintrusive.
For security reasons, you’ll want to run the Debian distribution as a non-root user. I’ve used my name, Chris, but you’re free to substitute your own.
As you can see, we’ve installed Git using the Debian package manager to have source control right inside the container.
Once your Dockerfile
is in place, navigate to the bottom-left corner of VSCode. Click the thunder icon, select:
- Open in container
- From Docker file
This action should result in a terminal display like the following!
chris@74e4594:/workspaces/go-dev-container:
For a basic Go application, create a main.go
file:
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
}
Initialise a module with:
go mod init your-module-name
Execute your application by entering:
go run main.go
Your terminal will display the following:
chris@f74e4594:/workspaces/go-dev-container$ go run main.go
Hello World!
chris@f74e45947:/workspaces/go-dev-container$
While this setup is robust, it lacks a debugging function. Ensure seamless debugging by first establishing a .vscode
directory, followed by inserting a launch.json
file:
{
"version": "0.2.0",
"configurations": [
{
"name": "Code",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"program": "${workspaceRoot}",
"env": {},
"args": [],
"showLog": true
}
]
}
Once you’ve done this, locate the debug icon on VSCode’s left sidebar. Click it, then select the code option.
As you can see from the image above you can stick breakpoints and debug your Go code inside the container!
Enjoy :)!
If this post sparks questions or thoughts, don’t hesitate to reach out.
My contact information is available in the about section.
You can find the source code in the following Github link.