>  기사  >  백엔드 개발  >  AWS에서 Docker를 사용하여 Go 애플리케이션 구축: 항목 추가 및 검색을 위한 RESTful 인터페이스 생성

AWS에서 Docker를 사용하여 Go 애플리케이션 구축: 항목 추가 및 검색을 위한 RESTful 인터페이스 생성

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-28 07:51:02179검색

소개

대부분의 Go 애플리케이션은 단일 바이너리 파일로 컴파일되지만 웹 애플리케이션에는 템플릿, 자산 및 구성 파일도 함께 제공됩니다. 동기화되지 않아 잘못된 배포가 발생할 수 있습니다.
Docker를 사용하면 애플리케이션을 실행하는 데 필요한 모든 것이 포함된 독립형 이미지를 만들 수 있습니다. 이 기사에서는 인스턴스에 설치된 Docker를 사용하여 Go 웹 애플리케이션을 배포하는 방법과 Docker가 개발 워크플로 및 배포 프로세스를 개선하는 데 어떻게 도움이 되는지 알아봅니다.

필요한 단계는 다음과 같습니다.

- 인스턴스(머신)를 시작하여 Docker를 구축하고 이동하세요.
신청

- 인스턴스에 Docker 설치
- 인스턴스에 Go 설치
- Go 애플리케이션용 코드 파일 생성
- 애플리케이션 테스트

Docker를 구축하고 Go를 수행할 인스턴스(머신)를 시작하세요.
신청

문서에 설명된 인스턴스 시작 및 연결과 동일한 단계를 찾을 수 있습니다.

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

참고: 보안 그룹을 선택했는지 확인하세요.

  • SSH 포트 22: SSH를 사용하여 인스턴스에 액세스하고 연결하려면
    시스템을 원격으로 관리하기 위한 프로토콜입니다.

  • HTTP 포트 8080: 이 포트(8080)에서 Go 애플리케이션을 실행하여 인터넷이나 로컬 네트워크에서 액세스하려면 이 포트가 열려 있어야 합니다.

- 인스턴스에 Docker 설치

우리가 만들 특정 워크플로 아키텍처는 Docker를 사용하여 통합 워크플로 환경을 제공합니다.
따라서 SSH를 통해 인스턴스에 연결하고 루트 권한을 얻은 후 다음 명령 자동화를 사용하여 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 업데이트 && apt- 캐시 정책 docker-ce

Docker 경험: 간단한 테스트 명령 docker -v를 실행하여 Docker가 제대로 작동하는지 확인하고 Docker 버전을 확인하세요.

Go 설치

Go 공식 홈페이지(https://go.dev/dl/)에서 Go를 다운로드하여 설치할 수 있습니다.
wget https://golang.org/dl/go1.20.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz
echo '내보내기 PATH=$PATH:/usr/local/go/bin' >> ~/.bash_profile
소스 ~/.bash_profile

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
어디서:
wget https://golang.org/dl/go1.20.linux-amd64.tar.gz 는 Go 바이너리를 다운로드하는 것입니다.

그리고
sudo tar -C /usr/local -xzf go1.20.linux-amd64.tar.gz는 tarball을 /usr/local에 추출하는 것입니다.
그리고
echo '내보내기 PATH=$PATH:/usr/local/go/bin' >> ~/.bash_profile은 PATH 환경 변수를 업데이트합니다.
프로필에 대한 변경 사항을 적용하려면 ~/.bash_profile 소스를 사용하세요

따라서 명령을 실행하고 ls 명령을 통해 실행을 확인한 후 다운로드한 파일을 표시합니다.

Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items
다음 코드를 사용하여 Go 애플리케이션을 초기화합니다.
go mod init my-go-app
Building a Go Application with Docker on AWS: Creating a RESTful Interface for Adding and Retrieving Items

이제 다음 명령을 사용하여 프로젝트 폴더를 생성해야 합니다.
mkdir <작업 이름>
그런 다음 다음 명령을 사용하여 현재 디렉터리를 변경합니다.
CD <작품명>
그래서 실행은 다음과 같습니다:

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

Go 애플리케이션용 코드 파일 만들기

main.go 파일

자세히 설명할 다음 기능과 코드가 포함된 main.go라는 새 파일을 만든 다음 모든 코드를 main.go 파일에 넣습니다.

  • 필요한 패키지를 가져오려면 다음 코드를 사용합니다.
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "os"
)
  • 데이터 구조 항목의 경우:
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

여기서 item은 식별자(ID)와 이름(Name)을 포함하는 데이터 구조입니다. 이러한 필드는 태그(json:"id" 및 json:"name".

)를 사용하여 JSON 형식으로 변환됩니다.
  • 항목 변수
var items []Item

서버 메모리에 저장된 항목의 조각입니다.

  • 기본 기능을 통해 구조는 새 요소 검색 또는 추가 및 간단한 HTML 페이지 표시에 대한 다양한 요청을 지시하는 것 외에도 포트(여기서는 포트 8080에 있음)를 읽어 배열됩니다.
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
    "os"
)
  • getItems 함수는 JSON 형식의 항목 목록을 반환합니다. 헤더의 콘텐츠 유형은 application/json으로 설정됩니다.
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
  • createItem 함수는 항목 목록에 새 항목을 추가합니다. 요청 본문에서 JSON 형식으로 데이터를 읽고, 항목에 기존 항목 수를 기준으로 ID를 할당하고, 추가된 항목을 JSON으로 반환합니다.
var items []Item
  • serveHome 기능은 환영 메시지(Go 앱에 오신 것을 환영합니다)와 데이터 액세스 링크가 포함된 간단한 HTML 페이지를 표시합니다.
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))
}

전체 main.go 파일은 다음과 같습니다.

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

이제 vim 또는 nano 명령을 통해 main.go 파일을 생성하고 파일에 위의 코드를 입력합니다. 여기서는 nano 명령을 사용합니다.

나노메인고

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

그런 다음 ctrl x, y(파일 저장)를 눌러 키보드에서 파일을 종료한 다음 enter

를 클릭하세요.

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

Docker 파일:

사용자가 이미지를 조합하기 위해 명령줄에서 호출할 수 있는 모든 명령이 포함된 텍스트 문서입니다.
Dockerfile은 Dockerfile의 지침을 읽어 이미지를 자동으로 빌드할 수 있습니다.

Dockerfile 만들기:

Docker로 컨테이너 이미지를 빌드하려면 빌드 지침이 포함된 Dockerfile이 필요합니다.
Dockerfile을 생성하고 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 명령 세부정보는 docker docs 홈페이지 https://docs.docker.com/guides/golang/build-images/에서 확인할 수 있습니다.

Dockerfile을 준비했으므로 이제 Go 애플리케이션용 Docker 이미지를 빌드할 차례입니다. 이미지는 다음과 같은 공식 Docker 이미지에서 만들 수 있습니다.

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
이미지가 성공적으로 빌드되었으며 다음 명령을 사용하여 빌드를 확인합니다.
도커 이미지

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

그런 다음 이미지를 빌드한 후 컨테이너를 실행하려면 다음을 사용합니다.

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

여기서 8080은 웹 서버의 포트이므로 실행 실행은 다음과 같습니다.

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

애플리케이션 테스트

- 컬 명령으로 Go 애플리케이션 테스트

curl 명령을 통해 Go 애플리케이션이 제대로 작동하는지 테스트하려면 다음을 수행하세요.

컬 http://localhost:8080/items

또는

curl http://<인스턴스의 공개 IPv4 주소>:8080/items

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

실행이 null입니다. 이는 애플리케이션이 작동 중이지만 아직 데이터가 없음을 의미합니다.

항목을 추가하려면 다음 명령을 사용하세요.

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

또는

curl -X POST -H "Content-Type: application/json" -d '{"name": "item"}' http://<인스턴스의 공개 IPv4 주소>:8080/items

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

다른 항목을 추가할 수 있습니다:

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

- 웹페이지에서 Go 애플리케이션 테스트

웹페이지를 통해 Go 애플리케이션이 제대로 작동하는지 테스트하려면 다음 단계를 따르세요.

  • 인스턴스로 돌아가서 확인란을 선택하세요.
  • 세부정보로 이동하여 공용 IPv4 주소를 복사하세요.
  • 포트 8080을 사용하는 공용 IPv4 주소를 브라우저에 붙여넣고 다음을 누릅니다. 들어가세요.

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

또는 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

참고자료:

  • https://dev.to/zahraajawad/building-a-jupyter-notebook-environment-in-docker-for-data-analytic-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

위 내용은 AWS에서 Docker를 사용하여 Go 애플리케이션 구축: 항목 추가 및 검색을 위한 RESTful 인터페이스 생성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.