(最新2020)Golang 使用Dockerfile 打包部署到 docker
https://blog.csdn.net/weixin_44042863/article/details/105872006
根据上文的配置,打包好了镜像
代码文件
package main
import (
"errors"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
func init() {
rand.Seed(time.Now().Unix())
file := "/dist/test.log";
logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
if err != nil {
panic(err)
}
log.SetOutput(logFile) // 将文件设置为log输出的文件
log.SetPrefix("[elk-test]")
log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
}
func main() {
var b=0
for {
go func() {
strs := []string{"fb-test1", "fb-test2", "fb-test3", "fb-test4", "fb-test5", "fb-test6", "fb-test7", "fb-test8", "fb-test9"}
a, _ := Random(strs, 1)
//now := time.Now()
//date := now.Format("2006-01-02 15:04:05")
userId := rand.Intn(10000)
b=b+1
result := "elon|" +strconv.Itoa(userId+1) + "|" + a +"|"+strconv.Itoa(b);
fmt.Println(result )
log.Println(result ) // log 还是可以作为输出的前缀
}()
time.Sleep(1*time.Second/100)
//time.Sleep(1*time.Second)
}
}
func Random(strings []string, length int) (string, error) {
if len(strings) <= 0 {
return "", errors.New("the length of the parameter strings should not be less than 0")
}
if length <= 0 || len(strings) <= length {
return "", errors.New("the size of the parameter length illegal")
}
for i := len(strings) - 1; i > 0; i-- {
num := rand.Intn(i + 1)
strings[i], strings[num] = strings[num], strings[i]
}
str := ""
for i := 0; i < length; i++ {
str += strings[i]
}
return str, nil
}
root@i-f1or71kf:/home/ubuntu/test# ls
Dockerfile README.md fb-test fb-test.go go.mod log
dockerfile代码修改了
FROM golang:alpine
# 为我们的镜像设置必要的环境变量
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64 \
GOPROXY="https://goproxy.cn,direct"
# docker容器里的工作目录
WORKDIR /dist
COPY go.mod .
COPY fb-test.go .
RUN go mod download
# 将代码复制到容器中
# 将我们的代码编译成二进制可执行文件 可执行文件名为 app
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -a -o app .
# 启动容器时运行的命令
CMD ["./app"]
build
docker build -t wenchajun/test .
run
docker run -itd wenchajun/test //后台运行
doceker ps|grep test //查看镜像的进程
docker logs -f e65 //查看该容器的日志 e65为容器id
docker exec -ti e65 /bin/sh //进入容器操作里面的文件,如果bash没有那么就找bin/sh
docker stop e65 //停止进程
接下来上传到dockerhub
运行容器,提交容器.png
登录docker账号然后push到dockerhub.png
docker commit 4100798343c7 wenchajun/test:v0.1
docker images|grep test
docker push wenchajun/test:v0.1
docker login
docker push wenchajun/test:v0.1
网友评论