Deploy a Dockerized Go application to Azure
Fullstack Developer and Tech Author
As a software engineer, one of your goals is to ensure that your product can be accessed globally by your customers. If your bug-free app works on localhost but fails in production due to a language version conflict, that won’t help customers, and it won’t impress your co-workers.
Docker was introduced to solve this “it works on my machine” problem. Using the power of containers, you can ensure consistency across different environments by packaging your application and its dependencies into a portable container image.
In this tutorial, I will show you how to Dockerize your Golang API. Using an already built Golang API project, you will build a container image out of it. Then, you’ll push the container image to the Azure Container Registry. I will then show you how to create an Azure web service as an application and connect the container image to it.
To wrap things up, I will guide you through creating a continuous integration and continuous deployment (CI/CD) pipeline to run automated tests and deployment using CircleCI.
Prerequisite
To follow along with this tutorial, you will need the following:
- Basic knowledge of Go programming language.
- Go installed on your system. Download instructions are available here.
- Docker Desktop installed on your local machine. You can follow Docker’s tutorial for Windows or macOS.
- A Microsoft Azure account.
- A CircleCI account.
- A GitHub account.
Setting up the demo project
To get started quickly, clone the Golang API project from GitHub. Review this tutorial to learn how this demo was built.
Run this command to download the project using Git:
git clone https://github.com/CIRCLECI-GWP/go-docker-azure.git
This will clone the project into a go-docker-azure folder within your development directory.
Running and testing the application
Next, move into the project folder and run the application:
cd go-docker-azure
go run main.go
The application will run on the default port 8080. Go to http://localhost:8080 to review it.
This endpoint returns a simple message. You can continue to test the remaining endpoints and run the unit tests to be sure that everything works as expected.
Creating a new company
Test this out using Postman or your preferred API testing tool. Send an HTTP POST request to http://localhost:8080/company. Use this data as the request payload:
{
"name":"Shrima Pizza",
"ceo": "Demo CEO",
"revenue":"300 million"
}
Retrieving the list of companies
To retrieve the list of companies, set an HTTP GET request to http://localhost:8080/companies.
Running the unit test
Now, open a new terminal window and run the test by issuing this command:
go test -v
At this point, the application works as expected, and the unit tests are passing. Stop the application from running using CTRL + C.
Creating a deployment strategy
As mentioned, the objective of this tutorial is to Dockerize and deploy the Golang project to an Azure web app. There is no need to modify the codebase other than the configuration file, so let’s go over the deployment strategy.
You will:
- Create a registry to host your container image on the Azure Container Registry (ACR) and get the Access key. ACR is a private registry owned by Microsoft for hosting Docker images. It works like DockerHub.
- Create a container image for the project, then build and run the container locally.
- Publish the Docker image to the Azure container registry.
- Create an Azure web app and link it with the published container image.
- Enable continuous deployment and create a configuration file to build and deploy your container image on CircleCI.
- Push the project to GitHub and connect with CircleCI.
- Deploy the container image to the Azure container registry.
Creating an Azure Container Registry
Next, you will create an Azure container registry that will store the image for this project. Go to the Azure portal homepage and click Create a resource. Select Infrastructure Services, then click Create under Container Registry.
On the registry creation page, add the details for the registry. Select a resource group (or click Create new), enter a registry name, and choose a location. I named mine godemo1. Set Pricing plan to Basic, the lowest-cost plan; the form defaults to Standard.
The Registry domain name field shows your registry’s login server. With the default Domain name label scope of Unsecure, it’s godemo1.azurecr.io. Any other scope adds a hash to the name, such as godemo1-abc123.azurecr.io. Use your own login server wherever this tutorial uses godemo1.azurecr.io.
Click Review + create. You will be redirected to a page where you can review the registry information. Click Create to set up a new registry instance.
Getting the access key from the registry
In this section, you will enable Docker access in the Azure Container Registry, which is crucial to the deployment process. It lets you remotely log in to the ACR through the CLI and push images to it.
After the registry resources have been created, open it and locate the Access keys link in the Settings section.
This will show you the registry name and login server. The admin user is off by default, so select the Admin user checkbox to enable it. Copy the username and any of the passwords, preferably the first one. Keep this handy; it will be used later in the tutorial.
Containerizing the application locally
Next, you will write a custom Docker file that will build a container image. From the root of the application, open the Dockerfile. Make sure its content matches this:
FROM golang:1.27-alpine
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]
This file uses golang:1.27-alpine as its base image. It then creates a new folder named app and adds all the content of the Golang project into it. Next, it sets the working directory in the container to the app folder and includes the command to run the project.
Building the Docker image
To build a Docker image for the project, run:
docker build -t godemo1.azurecr.io/go-demo:latest .
This command looks in the project for the Dockerfile and builds the container image based on the content of the Golang application. Note that the command uses the registry name and login server from the registry you created earlier. The benefit of this approach is that you can easily map the container image with the Azure container registry.
You will receive output when the container image has been built successfully.
Running the Docker image
Now that you have built the local version of the container image, run it with this command:
docker run -d -p 8080:8080 godemo1.azurecr.io/go-demo
This will run the app on the same port as earlier. Visit http://localhost:8080.
Pushing the Docker image to Azure Registry
Now, log in to the Azure container registry you created earlier and push the container image to it. Issue this command from the terminal:
docker login -u DOCKER_USER godemo1.azurecr.io
Replace DOCKER_USER with the username for the container registry. When prompted, enter the password from the container registry. Entering it at the prompt keeps the password out of your shell history.
Once you are logged in, use this command to push the image to the Azure registry:
docker push godemo1.azurecr.io/go-demo:latest
This deploys the image to the Azure registry. To check it, open the registry and select Services > Repositories > go-demo.
Creating an Azure web app for the container
Next, you will create an Azure web app and connect it with the container image. Go to the Azure portal homepage and click Create a resource. Select Web, then click Create under Web App.
You will be redirected to the Create Web App page. Select an Azure subscription and a resource group, and enter a name for the app. Below the name, the portal shows the app’s default domain, which includes a unique hash and the region, such as go-docker-demo-<hash>.eastus-01.azurewebsites.net. Set Publish to Container and Operating System to Linux, and pick the same region as your registry.
Under Pricing plans, check the Pricing plan field before you continue. The form can default to a Premium plan, and Free F1 or Basic B1 is enough for this tutorial.
Now, click the Container tab. Set Image Source to Azure Container Registry, choose your registry, and set Authentication to Admin credentials. Then select the go-demo image and the latest tag. Change Port to 8080, the port the Go app listens on; the default is 80.
Click Review + create. You will be redirected to a page where you can review the web app details. Click Create to set up a new Azure web app. If the deployment fails with “Operation cannot be completed without additional quota”, your subscription has no App Service quota for that plan in that region. Request an increase from the Quotas page in the portal, or try another plan or region.
Once the process is completed, visit your app’s default domain to review the app as deployed to Azure.
Enabling continuous deployment
To ensure that each time your Docker image is updated, the app will receive the update, you need to enable continuous deployment for the web app service.
First, let the registry’s webhook reach the app. New web apps have basic authentication turned off, and without it the webhook can fail with a 401 Unauthorized error. Open the web app, go to Configuration, and on the General settings tab set SCM Basic Auth Publishing Credentials to On. Click Save.
Then click Deployment Center under the Deployment section and turn on continuous deployment for the container. Depending on your portal version, this is the Continuous deployment setting on the Settings tab (click Save) or the Continuous deployment for the main container checkbox on the Containers tab (click Apply).
With continuous deployment selected, the web app will trigger a new deployment of the Golang application each time the Docker image is rebuilt on Azure Container Registry.
Automating deployments with CircleCI
Next, you need to add the pipeline configuration. This configuration instructs CircleCI to automate testing and run the commands to build and push the image to the Azure container registry.
At the root of your project, open the .circleci/config.yml file. Make sure the content matches this:
version: 2.1
orbs:
go: circleci/go@4.0.3
jobs:
build-and-run-test:
executor:
name: go/default
tag: "1.27"
steps:
- checkout
- go/load-mod-cache
- go/mod-download
- go/save-mod-cache
- run:
name: Run tests
command: go test -v
build-docker-image:
docker:
- image: cimg/go:1.27
steps:
- checkout
- setup_remote_docker:
docker_layer_caching: true
- run:
name: Build and push Docker image
command: |
docker build -t godemo1.azurecr.io/go-demo:latest .
echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin godemo1.azurecr.io
docker push godemo1.azurecr.io/go-demo:latest
workflows:
test-and-deploy:
jobs:
- build-and-run-test
- build-docker-image:
requires:
- build-and-run-test
These scripts contain two jobs:
- The
build-and-run-testjob pulls in the Go orb for CircleCI, which allows common Go-related tasks such as installing Go, downloading modules, and caching to be carried out. It then checks out the code from the remote repository and issues the command to run the test. - The
build-docker-imagejob builds the Docker container image for the project on CircleCI and pushes it to the Azure container registry. It turns on Docker layer caching, which speeds up repeat builds but costs 200 credits per job run.
The workflow ensures that the test is run successfully before building the container image and deploying it to Azure.
Next, you will need to set up a repository on GitHub and link the project to CircleCI. Review Pushing your project to GitHub for instructions.
Connecting your project with CircleCI
Log into your CircleCI account. If you signed up with your GitHub account, all your repositories will be available on the Projects page. Search for the go-docker-azure project:
Click Set up. In the Select your config.yml file dialog, choose Fastest to use the .circleci/config.yml in your repository, and enter the branch name (for the tutorial, you are using main). Click Set Up Project to complete the process.
If your organization uses the CircleCI GitHub App, you’ll start from Create Project instead and follow the prompts to connect the repository.
The first job will run successfully while the second will fail. This is because it requires the Azure container registry credentials.
Fixing the credential issue
To fix the credential issue, click Settings on the project’s pipeline page, then click Environment Variables. Click Add and create these two variables:
DOCKER_USERis the username for the container registry.DOCKER_PASSis the password from the container registry.
Go back to the failed workflow, click Rerun, and select Rerun workflow from start.
Your workflow will run successfully. You can make some changes to the codebase locally and push it to GitHub to be sure that continuous deployment has been implemented.
If you want more details about how your build went, you can review the details of this specific pipeline. CircleCI masks the values of project environment variables in job output, so the registry name appears as *******.azurecr.io because it matches DOCKER_USER.
Cleaning up resources
The registry and the App Service plan keep billing while they exist. When you’re done, delete the resource group you used for them: open Resource groups, select your group, and click Delete resource group.
Conclusion
As you learned in this tutorial, each time you update the project and push it to GitHub, CircleCI will use the configuration details to build a new container image and update the Azure container registry with it. And with continuous deployment enabled on the Azure web app, a webhook resource will be fired to push a new version of the container image to the web app.
I hope that you found this tutorial helpful. Check here for the complete source code for the project.