drol55885602
2017-08-29 21:23
浏览 140

在Docker容器中部署Golang应用程序

i need to deploy go restful app into Docker container.

My project has the following structure

go_proj

  |- bin
  |- src |
  |      |- com.example |
  |      |              |- web_service.go
  |      |
  |      |- github.com.gorilla.mux |
  |                                | - ...
  |- Dockerfile

How should my Dockerfile look like? And maybe I should download the library(mux) from the container?

图片转代码服务由CSDN问答提供 功能建议

我需要将安静的应用程序部署到Docker容器中。

我的项目 具有以下结构

go_proj

  |-bin 
 |-src | 
 |  |-com.example | 
 |  |  |-web_service.go 
 |  | 
 |  |-github.com.gorilla.mux | 
 |  |  -... 
 |-Dockerfile 
   
  
 
 

我的Dockerfile应该是什么样子? 也许我应该下载库(mux) 从容器中获取?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dptsivmg82908 2017-08-30 08:13
    已采纳

    I got some experience with deploying Go apps using Docker.

    TL;DR

    This is how my project looks like in ${GOPATH}/src/github.com/githubhandle/project

    main.go
    vendor.conf
    vendor/
        github.com/gorilla/mux
        github.com/sirupsen/logrus
        github.com/bshuster-repo/logrus-logstash-hook
        ...
    Dockerfile
    

    And the Dockerfile looks like this:

    FROM golang:1.8
    WORKDIR /go/src/app
    COPY . .
    RUN go-wrapper download
    RUN go-wrapper install
    EXPOSE [8080]
    ENTRYPOINT ["go-wrapper", "run", "main.go"]
    

    Pretty much

    Long answer

    In general, I like to put my Dockerfile inside the server directory:

    go/
        src/
            github.com/
                mygithub/
                    serverproject/
                        main.go
                        Dockerfile
    

    If I am using non standard packages in my projects such as (gorilla/mux) I would probably use vndr to create a vendor directory where I put all these packages and manage their versions.

    After that my Dockerfile would probably look like that:

    FROM golang:1.8
    WORKDIR /go/src/app
    COPY . .
    RUN go-wrapper download
    RUN go-wrapper install
    ENTRYPOINT ["go-wrapper", "run", "main.go"]
    

    Note You may want to automatically expose port number. For example, adding this line will expose port 8080 inside the container to the host.

    PORT 8080
    

    What is left to do is to build the image from within go/src/github.com/mygithub/serverproject:

    docker build -t serverproject .
    

    And to deploy it into a container:

    docker run -P --rm --name myserver1 serverproject
    

    If you want to pass arguments to the server you can do that like the following:

    docker run -P --rm --name myserver1 serverproject --arg1 --arg2=bla
    

    Note in case you didn't specify PORT in your Dockerfile and would like to expose it to the host, replace -P with -p before --name and specify <host-port>:<container-port>:

    docker run --rm -p 8080:8080 ...
    

    This will actually port forward from your host to the container.

    打赏 评论

相关推荐 更多相似问题