用docker弹性部署自己的服务
  

sailyang 2527

{{ttag.title}}
本帖最后由 sailyang 于 2018-11-5 15:42 编辑

OS:Ubuntu 16.04, 2G内存
docker:1.13.2
coding language: golang (gin web framework)

编码

将服务跑起来,是我们要完成的第一个步骤,而且是最重要的一个步骤。所以这一步需要仔细调试,为了方便,我就写的简单点。

app.go
package main

import (
        "os"
        "log"
                "github.com/gin-gonic/gin"
        "net/http"
        "time"
)

func GetHostName() string {
        hostname, err := os.Hostname()
        if err != nil {
                log.Fatal(err)
        }
        return hostname
}

func GetCurrentTime() string {
        timer := time.Now()
        return timer.String()
}

func startGinApp() {
        app := gin.Default()
        app.GET("/ping", func(context *gin.Context) {
                context.JSON(http.StatusOK, gin.H{
                        "message": "当前为您服务的主机为:" + GetHostName(),
                })
        })
        app.GET("/", func(context *gin.Context) {
                context.JSON(http.StatusOK, gin.H{
                        "message": "当前时间为:" + GetCurrentTime(),
                })
        })
        app.Run(":8080")
}

func main() {
        startGinApp()
}

把服务跑起来
go run app.go
1
curl一下看看服务是否正确跑起来了
➜  gin curl http://localhost:8080
{"message":"当前时间为:2018-10-14 11:31:23.016121853 +0800 CST m=+0.254631109"}%                                                                                                
➜  gin curl http://localhost:8080/ping
{"message":"当前为您服务的主机为:BiaodeMacBook-Pro.local"}%                                                                                                                     
➜  gin
1
2
3
4
5
制作Makefile

经过刚才的测试,代码可以正确跑起来了。但是要做到“一次编码,到处运行”,还是需要在构建阶段下点心思的,为了更好的维护,借助Makefile来规范构建过程,是比较合适的方法。

Makefile
# 这个是注释
# 开头可以声明一大堆变量名
BUILD_NAME ?= httpserver
COMPILER ?= go
BUILD ?= build


# 上方留一个空格,区分变量区和构建区
all: build test deploy clean

build:
        CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(COMPILER) $(BUILD) -o $(BUILD_NAME)

test:
        echo "test over."

deploy:
        echo "deploy over."

clean:
        echo "clean over."

.PHONY: build test deploy clean

构建服务
➜  gin ls
Makefile app.go
➜  gin make all
go build -o httpserver
echo "test over."
test over.
echo "deploy over."
deploy over.
echo "clean over."
clean over.
➜  gin ls
Makefile   app.go     httpserver
➜  gin ./httpserver &
[1] 6450
➜  gin [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env:        export GIN_MODE=release
- using code:        gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /ping                     --> main.startGinApp.func1 (3 handlers)
[GIN-debug] GET    /                         --> main.startGinApp.func2 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080

➜  gin curl http://localhost:8080/ping
[GIN] 2018/10/14 - 11:50:23 | 200 |     214.161µs |             ::1 | GET      /ping
{"message":"当前为您服务的主机为:BiaodeMacBook-Pro.local"}%                                                                                                                     
➜  gin

好了基本没什么问题,然后就可以通过scp命令将文件拷贝到linux服务器上了。

制作Dockerfile

由于golang构建出来的是二进制可执行程序,所以制作Dockerfile很简单。

Dockerfile
FROM ubuntu:latest
123@456.com

WORKDIR /app

EXPOSE 8080

ADD . /app

CMD ["./httpserver"]

构建自己的镜像
root@Server218 /h/d/g/d/httpserver# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ginserver           latest              6277a0180f4f        19 hours ago        101 MB
flaskindocker       latest              170c6c0a41db        22 hours ago        131 MB
python              2.7-slim            14dad3ead5f4        4 days ago          120 MB
docker/compose      1.23.0-rc2          dc59a0b5e981        5 days ago          45.6 MB
ubuntu              latest              cd6d8154f1e1        5 weeks ago         84.1 MB
root@Server218 /h/d/g/d/httpserver# docker build -t httpserver .
Sending build context to Docker daemon 17.07 MB
Step 1/6 : FROM ubuntu:latest
---> cd6d8154f1e1
Step 2/6 : MAINTAINER guopu 123@456.com
---> Running in 7106748df3ad
---> 0ae808029537
Removing intermediate container 7106748df3ad
Step 3/6 : WORKDIR /app
---> 7278bf9659e7
Removing intermediate container f7fdc76b19a8
Step 4/6 : EXPOSE 8080
---> Running in bedfabcb4b16
---> edf4c123f72f
Removing intermediate container bedfabcb4b16
Step 5/6 : ADD . /app
---> 36390e554a2f
Removing intermediate container b14cce9da53e
Step 6/6 : CMD ./httpserver
---> Running in 6682c8364717
---> b490fef8a9ca
Removing intermediate container 6682c8364717
Successfully built b490fef8a9ca
root@Server218 /h/d/g/d/httpserver# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
httpserver          latest              b490fef8a9ca        4 seconds ago       101 MB
ginserver           latest              6277a0180f4f        19 hours ago        101 MB
flaskindocker       latest              170c6c0a41db        22 hours ago        131 MB
python              2.7-slim            14dad3ead5f4        4 days ago          120 MB
docker/compose      1.23.0-rc2          dc59a0b5e981        5 days ago          45.6 MB
ubuntu              latest              cd6d8154f1e1        5 weeks ago         84.1 MB
root@Server218 /h/d/g/d/httpserver#

让服务在docker中跑起来
root@Server218 /h/d/g/d/httpserver# docker run -d  -p 8000:8080 httpserver
ebb1926206cdaf16eae9f4e13d5a7e70dd695da91463b438f77e45c6f65d3323
root@Server218 /h/d/g/d/httpserver# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
ebb1926206cd        httpserver          "./httpserver"      4 seconds ago       Up 3 seconds        0.0.0.0:8000->8080/tcp   nostalgic_wright
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:ebb1926206cd"}~                                                                                                                                 

root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/
{"message":"当前时间为:2018-10-14 04:14:29.116207751 +0000 UTC"}~                                                                                                               

root@Server218 /h/d/g/d/httpserver#

弹性服务

一个容器跑一个服务,有些服务访问峰差很大的场景,就需要做下弹性适配,于是需要用一下docker swarm服务。这个在linux环境下需要进行安装。具体可以参考官网链接: https://github.com/docker/compose/releases
其运行以来一个YAML配置文件,具体细节不多说,上手吧。

docker-compose.yml
version: "3"
services:
    web:
        image: httpserver:latest
        deploy:
            replicas: 5
            resources:
                limits:
                    cpus: "0.1"
                    memory: 50M
            restart_policy:
                condition: on-faliure
        ports:
            - "8000:8080"
        networks:
            - webnet
networks:
    webnet:

初始化swarm
root@Server218 /h/d/g/d/httpserver# docker swarm init
Swarm initialized: current node (atiuy6c8k1qcig5w3br1bwf0n) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join \
    --token SWMTKN-1-5e0sj0glbwl5w5rqytyqokeg91n7piwdyw9ik598x0poiz5s20-do445zhrdr5io93lplov42c2y \
    172.31.237.68:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

root@Server218 /h/d/g/d/httpserver#

发布服务到swarm中
root@Server218 /h/d/g/d/httpserver# docker stack deploy -c docker-compose.yml httpserver
Creating service httpserver_web
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver# docker stack ps httpserver
ID            NAME              IMAGE              NODE       DESIRED STATE  CURRENT STATE           ERROR  PORTS
kvpvwptlj44c  httpserver_web.1  httpserver:latest  Server218  Running        Running 14 seconds ago
6549g79dz5iz  httpserver_web.2  httpserver:latest  Server218  Running        Running 14 seconds ago
xkz42mnetmws  httpserver_web.3  httpserver:latest  Server218  Running        Running 14 seconds ago
rpziwzmpogn2  httpserver_web.4  httpserver:latest  Server218  Running        Running 14 seconds ago
y2kfe8bp09ld  httpserver_web.5  httpserver:latest  Server218  Running        Running 6 seconds ago
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:a5419e3d3f9c"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:f636819bd9c4"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:97a6e3c9a064"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:7f1b28e14970"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:0ce251661188"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:a5419e3d3f9c"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver#

实例弹性变化
具体的操作只需要修改docker-compose.yml中的replicas的数量即可。然后重新使用:
docker stack deploy -c docker-compose.yml httpserver
1
发布就可以了,可以看出swarm管理下的实例会进行自动的负载均衡。

关停服务
root@Server218 /h/d/g/d/httpserver# docker stack ls
NAME        SERVICES
httpserver  1
root@Server218 /h/d/g/d/httpserver# docker stack rm httpserver
Removing service httpserver_web
Removing network httpserver_webnet
root@Server218 /h/d/g/d/httpserver# docker stack ls
NAME  SERVICES
root@Server218 /h/d/g/d/httpserver#

关掉swarm
root@Server218 /h/d/g/d/httpserver# docker swarm leave --force
Node left the swarm.
root@Server218 /h/d/g/d/httpserver#

总结

root@Server218 /h/d/g/d/httpserver# ls -al
total 16688
drwxr-xr-x 2 root root     4096 Oct 14 12:20 ./
drwxr-xr-x 5 root root     4096 Oct 14 12:00 ../
-rw-r--r-- 1 root root      121 Oct 14 12:11 Dockerfile
-rw-r--r-- 1 root root      362 Oct 14 12:01 Makefile
-rw-r--r-- 1 root root      682 Oct 14 12:01 app.go
-rw-r--r-- 1 root root      385 Oct 14 12:27 docker-compose.yml
-rwxr-xr-x 1 root root 17063672 Oct 14 12:03 httpserver*
root@Server218 /h/d/g/d/httpserver#

基本上,在docker中弹性部署自己的服务就结束了,基本上也能满足需要。

打赏鼓励作者,期待更多好文!

打赏
暂无人打赏

好心情能长寿 发表于 2018-11-5 22:26
  
充充电了
sangfor_闪电回_小六 发表于 2018-11-8 16:20
  
表示完全看不懂
发表新帖
热门标签
全部标签>
每日一问
2024年技术争霸赛
技术盲盒
GIF动图学习
技术笔记
干货满满
产品连连看
新版本体验
2023技术争霸赛专题
功能体验
技术咨询
每周精选
标准化排查
通用技术
信服课堂视频
华北区交付直播
答题自测
流量管理
华北区拉练
技术晨报
信服圈儿
自助服务平台操作指引
场景专题
畅聊IT
技术圆桌
用户认证
排障笔记本
秒懂零信任
安装部署配置
VPN 对接
终端接入
玩转零信任
专家问答
在线直播
MVP
网络基础知识
升级
安全攻防
上网策略
测试报告
日志审计
问题分析处理
每日一记
运维工具
云计算知识
原创分享
解决方案
sangfor周刊
项目案例
SANGFOR资讯
专家分享
技术顾问
信服故事
SDP百科
功能咨询
授权
设备维护
资源访问
地址转换
虚拟机
存储
迁移
加速技术
产品预警公告
S豆商城资讯
技术争霸赛
「智能机器人」
追光者计划
深信服技术支持平台
社区帮助指南
答题榜单公布
纪元平台
卧龙计划
天逸直播
以战代练
山东区技术晨报
文档捉虫活动
齐鲁TV
北京区每日一练
故障笔记

本版达人

新手68983...

本周分享达人

零和一网络

本周提问达人