Home Backend Development Golang Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Oct 28, 2024 am 07:51 AM

Introduction

While most Go applications are compiled into a single binary file, web applications also come with templates, assets, and configuration files; these can get out of sync and cause erroneous deployments.
Docker allows us to create a standalone image with everything our application needs to run. In this article, we will learn how to deploy a Go web application using Docker installed on an instance, and how Docker can help you improve your development workflow and deployment process.

The steps we need will be as follows:

- Launch an instance (your machine)to build Docker on and the Go
application

- Install Docker in instance
- Installing Go in instance
- Create code files for your Go application
- Application Testing

Launch an instance (your machine)to build Docker on and the Go
application

You can find the same steps of the launch and connect of instance described in the article:

https://dev.to/zahraajawad/building-a-jupyter-notebook-environment-in-docker-for-data-analysis-on-aws-ec2-376i

Note: Make sure you choose the security group:

  • SSH-Port 22: To access and connect to the instance using SSH
    protocol to manage the system remotely.

  • HTTP-Port 8080: To run the Go application on this port (8080) to access it from the Internet or local network, this port must be open.

- Install Docker in our instance

The specific workflow architecture we will create uses Docker to provide an integrated workflow environment.
So after connecting to the instance via SSH and obtaining the root privilege, use the following command automation to install Docker:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - && sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" && sudo apt-get update && apt-cache policy docker-ce

Docker experience: Run a simple test command docker -v to check that Docker is working properly and to see the Docker version:

Installing Go

You can install Go by downloading it from the official Go website https://go.dev/dl/
wget https://golang.org/dl/go1.20.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bash_profile
source ~/.bash_profile

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
where :
wget https://golang.org/dl/go1.20.linux-amd64.tar.gz is to download Go binary.

and
sudo tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz is to extract the tarball to /usr/local.
and
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bash_profile to Update the PATH environment variable.
and source ~/.bash_profile to apply the changes made to the profile

So after executing the commands and verifying the execution through the command ls to show the downloaded files:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
Initialize the Go application with the following code:
go mod init my-go-app
Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Now we need to create a project folder by the command:
mkdir
Then change the current directory by the command :
cd
so the execution is :

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Create code files for your Go application

The main.go file

We create a new file called main.go which contains the following functions and codes which we will explain in detail and then we put all the codes in the main.go file:

  • To import the necessary packages we use the code:
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "os"
)
Copy after login
Copy after login
  • For the data structure item:
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
Copy after login
Copy after login

where itemis a data structure containing an identifier (ID) and a name (Name). These fields are converted to JSON format using tags (json:"id" and json:"name".

  • items variable
var items []Item
Copy after login
Copy after login

which is a slice of items stored in server memory.

  • Through the main function the structures are arranged by reading the port (here it will be on port 8080) in addition to directing the various requests from retrieving or adding a new element and displaying a simple HTML page.
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "os"
)
Copy after login
Copy after login
  • The function getItems returns a list of items in JSON format. The content type in the header is set to application/json.
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
Copy after login
Copy after login
  • The createItem function adds a new item to the items list. The data is read from the Request Body in JSON format, the item is assigned an ID based on the number of existing items, and the added item is returned as JSON.
var items []Item
Copy after login
Copy after login
  • The serveHome function displays a simple HTML page with a welcome message (Welcome to the Go App) and links to access the data.
func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    router := mux.NewRouter()
    router.HandleFunc("/items", getItems).Methods("GET")
    router.HandleFunc("/items", createItem).Methods("POST")
    router.HandleFunc("/", serveHome).Methods("GET")

    log.Printf("Server is running on port %s...\n", port)
    log.Fatal(http.ListenAndServe(":"+port, router))
}
Copy after login

So the entire main.go file is:

func getItems(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(items)
}
Copy after login

Now through the command vim or nano create the main.go file and put above code in the file, here we will use the command nano:

nano main.go

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
And past the codes:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

then exit the file from the keyboard by ctrl x then y (to save the file) then click enter

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Dockerfile:

Is a text document that contains all the commands a user could call on the command line to assemble an image.
Dockerfile can build images automatically by reading the instructions from a Dockerfile.

Create a Dockerfile:

A Dockerfile with build instructions is required to build a container image with Docker.
We create a Dockerfile and add the following code in the same way as before through the command nano Dockerfile:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Dockerfile command details can be found on the docker docs homepage https://docs.docker.com/guides/golang/build-images/

Now that we have prepared the Dockerfile, it is time to build a Docker image for the Go application. The image can be made from the official Docker images which are:

docker build -t my-go-app .

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
The image is successfully built, and to make sure of the build by using the command:
docker images

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Then to run the container after building the image, we use:

docker run -p 8080:8080 my-go-app

where 8080 is the port of the web servers, so the execution run is:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Application Testing

- Test the Go application by the curl command

To test whether the Go application works properly through the curl command by:

curl http://localhost:8080/items

or

curl http://:8080/items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

the execution is null, which means the application is working but we have no data yet.

To add an item, by the command:

curl -X POST -H "Content-Type: application/json" -d '{"name": "item"}' http://localhost:8080/items

or

curl -X POST -H "Content-Type: application/json" -d '{"name": "item"}' http://:8080/items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

so the execution of adding:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

we can add another item:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

- Test the Go application by the web page

To test whether the Go application works properly through the web page, the following steps:

  • Go back to the instance and select it by the checkbox.
  • Go to the Details and copy the Public IPv4 address.
  • Paste the public IPv4 address with port 8080 into the browser and press Enter.

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

The web page is working and when we press on items on the page we obtain the items that add by the curl command.

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Or can press the checkbox of Pretty-print:

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

References:

  • https://dev.to/zahraajawad/building-a-jupyter-notebook-environment-in-docker-for-data-analysis-on-aws-ec2-376i
  • https://semaphoreci.com/community/tutorials/how-to-deploy-a-go-web-application-with-docker
  • https://hub.docker.com/_/golang
  • https://docs.docker.com/guides/golang/build-images/
  • https://github.com/gorilla/mux

The above is the detailed content of Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

See all articles