一、Docker简述
注:Docker的安装
1.什么是Docker
笼统一点理解的话,你可以把它看成一个轻量级的VMware虚拟机,
2.优点
启动速度快
占用资源少
部署方便
隔离性好
易于管理
可持久化
3.怎么使用Docker
参考 Docker命令大全
二、使用Docker制作Golang微服务镜像并运行
1.准备文件practice.go和Dockerfile文件放同一目录,并进入目录下
packagemainimport("github.com/gin-gonic/gin")funcmain(){//创建一个默认的路由引擎r:=gin.Default()//GET:请求方式;/hello:请求的路径//当客户端以GET方法请求/hello路径时,会执行后面的匿名函数r.GET("/hello",func(c*gin.Context){//c.JSON:返回JSON格式的数据c.JSON(200,gin.H{"message":"Helloworld!",})})//启动HTTP服务,默认在0.0.0.0:8080启动服务r.Run()}
FROMalpineRUNsed-i's/https/http/'/etc/apk/repositoriesRUNapkaddcurlRUNapkupdate--no-cache&&apkadd--no-cacheca-certificatestzdataENVTZAsia/ShanghaiWORKDIR/appCOPY./practice/app/practice#COPY--from=builder/app/etc/app/etcEXPOSE8080CMD["./practice"]
2.编译alpine二进制文件
xxxx@ubuntu:~/MyProject/Practice$goenv-wGOOS=linuxxxxx@ubuntu:~/MyProject/Practice$goenv-wCGO_ENABLED=0xxxx@ubuntu:~/MyProject/Practice$gobuildpractice.go
当前目录下生成了可执行文件practice
xxxx@ubuntu:~/MyProject/Practice$tree.├──Dockerfile├──practice└──practice.go
可以在linux环境下执行
xxxx@ubuntu:~/MyProject/Practice$./practice[GIN-debug][WARNING]CreatinganEngineinstancewiththeLoggerandRecoverymiddlewarealreadyattached.[GIN-debug][WARNING]Runningin"debug"mode.Switchto"release"modeinproduction.-usingenv:exportGIN_MODE=release-usingcode:gin.SetMode(gin.ReleaseMode)[GIN-debug]GET/hello-->main.main.func1(3handlers)[GIN-debug]EnvironmentvariablePORTisundefined.Usingport:8080bydefault[GIN-debug]ListeningandservingHTTPon:8080
验证结果
3.制作Docker镜像
root@ubuntu:/home/xxxx/MyProject/Practice#dockerbuild-tpractice.SendingbuildcontexttoDockerdaemon15.51MBStep1/9:FROMalpine--->6dbb9cc54074Step2/9:RUNsed-i's/https/http/'/etc/apk/repositories--->Usingcache--->3fda4e22207cStep3/9:RUNapkaddcurl--->Usingcache--->14273f662442Step4/9:RUNapkupdate--no-cache&&apkadd--no-cacheca-certificatestzdata--->Usingcache--->6d2f22d57416Step5/9:ENVTZAsia/Shanghai--->Usingcache--->b4a0dbb84330Step6/9:WORKDIR/app--->Usingcache--->b97a1d5811c7Step7/9:COPY./practice/app/practice--->c0ff57ecd31aStep8/9:EXPOSE8080--->Runninginc76c2a2c7a6aRemovingintermediatecontainerc76c2a2c7a6a--->c2c88532e0f9Step9/9:CMD["./practice"]--->Runningin6a43d98e96baRemovingintermediatecontainer6a43d98e96ba--->4b84b2b9664fSuccessfullybuilt4b84b2b9664fSuccessfullytaggedpractice:latest
可以看到生成的镜像
root@ubuntu:/home/xxxx/MyProject/Practice#dockerimagesREPOSITORYTAGIMAGEIDCREATEDSIZEpracticelatest4b84b2b9664f3minutesago26.5MB
4.运行镜像
root@ubuntu:/home/xxxx/MyProject/Practice#dockerrun--net=host--namepractice-dpractice818293911f4aa67541a88f99c9161f8db295899e5e2f71b8a00b30532f542226
可以看到运行的容器
root@ubuntu:/home/caoxun/MyProject/Practice#dockerpsCONTAINERIDIMAGECOMMANDCREATEDSTATUSPORTSNAMES818293911f4apractice"./practice"44secondsagoUp43secondspractice