用docker弹性部署自己的服务
  很久不看docker的东西了,之前了解的一些基本命令都忘得差不多了,适逢工作需要,再来复习巩固下。今天想完成的是:借助docker不部署下自己的服务。
  
  环境准备
  
  都说“巧妇难为无米之炊”,所以还是需要先准备下的。
  
  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
  
  制作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
  
  MAINTAINER guopu marksinoberg@gmail.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 www.tygj178.com daemon 17.07 MB
  
  Step 1/6 : FROM ubuntu:latest
  
  ---> cd6d8154f1e1
  
  Step 2/6 : MAINTAINER guopu marksinoberg@gmail.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 . www.ysyl157.com /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/ www.xinghenyule.com 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          ".www.dfgjpt.com /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#
  
  12
  
  至此,看起来服务已经成功在服务器环境下的docker中运行了。
  
  弹性服务
  
  一个容器跑一个服务,有些服务访问峰差很大的场景,就需要做下弹性适配,于是需要用一下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-www.yinmaoyule178.com   faliure
  
  ports:
  
  - "8000:8080"
  
  networks:
  
  - webnet
  
  networks:
  
  webnet:
  
  初始化swarm
  
  root@Server218 /h/d/g/d/httpserver# docker swarm init
  
  Swarm initialized: current node www.ylouyi3.com(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弹性部署自己的服务的更多相关文章
- .net core 微服务架构-docker的部署-包括网关服务(Ocelot)+认证服务(IdentityServer4)+应用服务(asp.net core web api)
		
本文主要介绍通过Docker来部署通过.Net Core开发的微服务架构,部署的微服务主要包括统一网关(使用Ocelot开发).统一认证(IdentityServer4).应用服务(asp.net c ...
 - 十一、Docker搭建部署SpringCloud微服务项目Demo
		
环境介绍 技术选型:SpringCloud&SpringCloud Alibaba&Docker 微服务模块划分: 员工模块:ems-employees 部门模块:ems-depart ...
 - docker swarm部署spring cloud服务
		
一.准备docker swarm的集群环境 ip 是否主节点 192.168.91.13 是 192.168.91.43 否 二.准备微服务 ①eureka服务 application.y ...
 - Microservices  微服务概念和优点    自治  弹性 级联故障  微服务的问题   CAP   分布式事务                  修改一个服务并对其部署而不影响其他任务服务
		
https://en.wikipedia.org/wiki/Microservices https://zh.wikipedia.org/wiki/微服務 微服務 (Microservices) 是一 ...
 - 在docker里部署网络服务
		
之前试着玩玩docker有一阵子了,今天算是头一回正式在docker里部署网络服务. 本来想和lxc差不多的东西那自然是手到擒来,没想到还是改了很多. 第一个遇到的问题是,远程连到docker宿主机干 ...
 - 基于docker 如何部署surging分布式微服务引擎
		
1.前言 转眼间surging 开源已经有1年了,经过1年的打磨,surging已从最初在window 部署的分布式微服务框架,到现在的可以在docker部署利用rancher 进行服务编排的分布式微 ...
 - 【docker】docker部署spring boot服务,但是docker logs查看容器输出控制台日志,没有日志打印,日志未打印,docker logs不打印容器日志
		
如题: docker部署spring boot服务,但是docker logs查看容器输出控制台日志,没有日志打印,日志未打印,docker logs不打印容器日志 场景再现: docker部署并启动 ...
 - Docker Compose部署GitLab服务,搭建自己的代码托管平台(图文教程)
		
场景 Docker-Compose简介与Ubuntu Server 上安装Compose: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...
 - docker下部署服务
		
一.zabbix部署 需求: 因最近项目过多,人力监控耗费时间,打算部署一个zabbix,但又不想部署在宿主机上,就想起了docker,docker快速的移植性是最大的亮点,好了,言归正传开始干. 部 ...
 
随机推荐
- git clone  fatal: unable to access 'https://github.com/carlon/demo.git/': Failed to connect to github.com port 443: Timed out
			
$ git config --global http.proxy $ git config --global --unset http.proxy 虽然之前没有设置代理,但是不知道为什么执行以上代码之 ...
 - jmeter并发定时器
			
jmeter并发定时器
 - 关于在filter中获取WebApplicationContext的实践
			
网上很多说法,诸如: <param-name>contextConfigLocation</param-name> <param-value> classpath: ...
 - ubuntu 14.04 安装redis
			
root@hett-PowerEdge-T30:~# sudo apt-get install redis-server Reading package lists... DoneBuilding d ...
 - 设置windows status bar隐藏
			
info.plist View controller-based status bar appearance 为 NO CGContextSaveGState: invalid context 0x0 ...
 - 如何启动Intel VT-x
			
如何启动Intel VT-x 5 在64bit win7系统下安装了Vmware10,然后安装64位的UbuntuKylin 14.04,想要打开UbuntuKylin,弹出如下对话框: 请问该如何启 ...
 - Python 中函数(Function)的用法
			
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.Python提供了许多内建函数,比如print().input(),也可以自己创建函数, ...
 - soapui测试https双向验证p12项目
			
1.准备好p12 和jsk秘钥文件 2.配置soapui ssl 其中: 1:jks就是放在trustStore那里,密码填写为 106075 2:p12放到keystore,密码填写:180000 ...
 - 题解 P1189 SEARCH
			
(传送门)[https://www.luogu.org/problemnew/show/P1189] 先反省一波:我以后再也不用getchar()+scanf了(日常爆零) 算是比较裸的搜索吧,在下用 ...
 - 【简●解】 LG P2730 【魔板 Magic Squares】
			
LG P2730 [魔板 Magic Squares] [题目背景] 在成功地发明了魔方之后,鲁比克先生发明了它的二维版本,称作魔板.这是一张有8个大小相同的格子的魔板: 1 2 3 4 8 7 6 ...