Setting Up a Dev Container for Go
-
Primary author: Sanjana Gopalswamy
-
Reviewer: Caitlin Estrada
Prerequisites
Before getting started, ensure you have the following installed on your system:
- Visual Studio Code – A lightweight code editor that supports DevContainers.
- Docker – Required to run the DevContainer.
- VS Code Extensions:
- Dev Containers (install from VS Code marketplace)
- Go (Made by the Go Team at Google)
Step 1: Create a New Project Directory
-
Open the terminal and create a new directory for your project:
-
Initialize a new Git repository:
Step 2: Add Development Container Configuration
- Open the
comp423-go-tutorial
directory in VS Code:- Go to File > Open Folder and select your project directory.
- Install the Dev Containers extension:
- Open the Extensions Marketplace (Ctrl+Shift+X), search for "Dev Containers," and install it.
- Create a
.devcontainer
directory in the project root:
Tip:
You can also create a new file through VSCode's Explorer panel.
- Inside the
.devcontainer
directory, create adevcontainer.json
file with the following content:
{
"name": "COMP423 Go Tutorial",
"image": "mcr.microsoft.com/devcontainers/go:latest",
"customizations": {
"vscode": {
"extensions": ["golang.go"]
}
},
"postCreateCommand": "go mod init comp423-go-tutorial"
}
Explanation of devcontainer.json
:
-
name
: Specifies a descriptive name for the DevContainer. -
image
: Uses Microsoft's official Go DevContainer image. -
customizations
: Installs the official Go extension for VS Code. -
postCreateCommand
: Initializes a Go module for dependency management.
Step 3: Reopen in Dev Container
- Open the command palette in VS Code (Cmd+Shift+P) and run: Dev Containers: Reopen in Container
- Wait for the container to build and start.
Step 4: Verify Go Installation
- Open a terminal inside the container and run:
Look Out
Make sure it outputs a recent Go version! (i.e. Such as go version ex. Go 1.23)
Step 5: Create a Hello COMP423 Program
- Create a new file
main.go
in the project root with the following content: - Initialize the Go module:
Step 6: Running and Building the Go Program
- Run the Go program directly:
Did you know?
This command compiles and runs the program in a single step!
- Build the Go program:
hello_comp423
.
3. Unlike go run, the compiled binary does not need the Go environment to execute.
Explanation of Commands
-
go run
: Compiles and runs the program temporarily without generating an executable file. -
go build
: Compiles the source code and produces a standalone binary, similar to using gcc for C programs.
Running the binary: Executes the compiled program without involving the Go runtime directly.
Success!
You have successfully set up a DevContainer for Go, written a "Hello COMP423" program, and learned how to run and build it. You can now continue developing Go applications within a consistent and containerized environment.