登录
首页 >  Golang >  Go问答

在 Docker 环境下使用 AWS EC2 上的 Golang GO 端点获取 JSON 数据时遇到了困难

来源:stackoverflow

时间:2024-03-03 11:24:26 420浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《在 Docker 环境下使用 AWS EC2 上的 Golang GO 端点获取 JSON 数据时遇到了困难》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我在使用 docker 文件向 aws 上的 /biz 端点发出 get 请求时遇到了困难。我根据本课程制作了以下项目,很想听听您的见解。

我在终端中运行了以下所有命令

docker build -t projectname
docker tag projectname username/projectname
docker push username/projectname
ssh -i ~/.ssh/projectaws.pem ec2-user@[public-dns

aws ec2 的内部终端

sudo yum update -y
sudo yum install -y dockersudo service docker start
sudo usermod -a -g docker ec2-user
docker run -d -p 80:80 usernam/projectname

当我访问我的 ipv4 公共 ip http://xxx.xxx.xxx/biz 时,除了“无法访问此站点”之外没有任何返回,当 docker 在本地运行时,它可以在 localhost:80/biz 上运行。你认为我缺少什么吗?就像 dockerfile 一样?缺少进口? aws 设置?端点?还是 main.go 本身?提前致谢!

# dockerfile from docker
# start from a debian image with the latest version of go installed
# and a workspace (gopath) configured at /go.
from golang

# copy the local package files to the container's workspace.
add . /go/src/github.com/seintun/dinesty.ninja-backend
workdir /go/src/github.com/seintun/dinesty.ninja-backend

# build the outyet command inside the container.
run go get ./
run go build

# run the outyet command by default when the container starts.
entrypoint /go/bin/dinesty.ninja-backend

# document that the service listens on port 8080.
expose 8080

package main

import (
  "log"
  "net/http"
  "os"

  "github.com/gorilla/handlers"
  "github.com/gorilla/mux"
  ctrl "github.com/username/projectname/controllers"
)

func main() {
    r := mux.newrouter()
    r.handlefunc("/biz", ctrl.fetchbiz).methods("get")
rlog := handlers.logginghandler(os.stdout, r)
	if err := http.listenandserve(":8080", rlog); err != nil {
		log.fatal(err)
	}
}

// 如果你想知道 ctrl.fetchbiz 做了什么,它只是从 mongodb 获取 json 包ctrl

import (
  "encoding/json"
  "io/ioutil"
  "log"
  "net/http"

  . "github.com/username/projectname/models"
  "gopkg.in/mgo.v2/bson"

  mgo "gopkg.in/mgo.v2"
)

// FetchBiz return list of bizs
func (b *BizDAO) FetchBiz() ([]Biz, error) {
    query := bson.M{"active": true}
    var bizs []Biz
    err := db.C(BCOLLECTION).Find(query).All(&bizs)
    return bizs, err
}

解决方案


您的网络服务器服务于端口 8080 if err := http.ListenAndServe(":8080", rLog); err != nil { 当您公开并访问端口 80 docker run -d -p 80:80 usernam/projectname

当您使用 docker run -d -p 80:8080 usernam/projectname 时,您的 Web 服务应该可以在主机的端口 80 上访问。

本篇关于《在 Docker 环境下使用 AWS EC2 上的 Golang GO 端点获取 JSON 数据时遇到了困难》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>