Before I wrote how to deploy the Golang program to the server, this time we write how to use Docker to deploy my Golang, of course, if you want to deploy to the Docker
inside, Docker
it must be installed, you can click here to see the installation steps.
Wen/Qian Yi
This article may not be suitable for go and Docker
0 basic people to read, need to have a certain basic knowledge.
Dependency knowledge
- Go cross-compiling basics
- Docker Basics
- Dockerfile Custom Mirroring Basics
- Docker-compose compiling the basis for writing a document
Of course, will not be able to follow this step to deploy the completion, but may be in the middle if a small problem, will not know how to solve, of course, you can also leave a message.
I developed tests on a MAC environment, and if you're on Windows you might have a little bit of a discrepancy, but there shouldn't be a big problem.
I. Environment-dependent
Second, write a Golang Web program
I'll write a simple Hello World program here, the listening port is port 80.
Create a new main.go
file with the following contents:
package mainimport ( "fmt" "log" "net/http")func sayHello(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello world")}func main() { http.HandleFunc("/", sayHello)//注册URI路径与相应的处理函数 log.Println("【默认项目】服务启动成功 监听端口 80") er := http.ListenAndServe("0.0.0.0:80", nil) if er != nil { log.Fatal("ListenAndServe: ", er) }}
Third, compiled into Linux under the package
I developed on the Mac, need to use the cross-compilation of Go, if the cross-compilation is not familiar with, you can check the following document, or directly copy my command below to compile.
We are going to run Docker
inside, base golang
This image to run, so we need to compile it into i386
a processor-compatible program.
sudo env GOOS=linux GOARCH=386 go build main.go
After this compilation, the local will be a more main
program, temporarily do not have to take care of it to spare the line.
Iv. using Dockerfile
A custom image of our go program
Create a new folder, create a new file in it, and Dockerfile
then create a new app
, script
two file inside. Put the previous step of the main
program into the app
folder inside, script
create a new script file inside, the contents of the build.sh
file first, and so on will say.
The specific file structure is this way.
.├── Dockerfile├── app│ └── main└── script └── build.sh
The following is the writing of the contents of the content Dockerfile
, I first on the code: