社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
实现通过docker部署golang web服务功能
在/Users/admin/go_mod
新建go工程,目录名为hellodocker,新建文件main.go
package main
import (
"fmt"
"net/http"
)
func handlerHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello docker")
}
func main() {
http.HandleFunc("/", handlerHello)
http.ListenAndServe(":8080", nil)
}
进入hellodocker目录,执行
go run main.go
最后执行
curl http://localhost:8080/
返回“hello docker”则表示web服务运行成功
1.在工程目录hellodocker下,新建dockerfile
文件
FROM golang:latest
MAINTAINER "kl023011@gmail.com"
WORKDIR /Users/admin/go_mod/hellodocker
ADD . /Users/admin/go_mod/hellodocker
RUN go build .
EXPOSE 8080
ENTRYPOINT ["./hellodocker"]
FROM 母镜像
MAINTAINER 维护者信息
WORKDIR工作目录
ADD 将文件复制到镜像中
RUN 执行操作
EXPOSE 监听端口
ENTRYPOINT 程序入口
2.进入hellodocker目录,打开终端输入
docker build -t hellodocker .
docker build 构建镜像
hellodocker 镜像名字为hellodocker
. (点号) dockerfile目录为当前目录
构建成功后输出
3.查看docker镜像
在终端中输入
docker images hellodocker
里面显示了本机所有docker的镜像与其基本信息
在终端输入
docker run -p 8080:8080 -d hellodocker
docker run 运行docker镜像
-p 8080:8080 将宿主机(也就是本机)的8080端口映射到容器的8080端口,此处需要先确认本机的8080端口并未被占用,容器的8080端口是否在监听
hellodocker 镜像名(也可以是镜像id)
-d 后台运行
启动容器后执行
curl http://localhost:8080/
返回“hello docker”则表示通过docker搭建golang web服务成功
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!