Docker-compose basic example

在本节中,我们快速浏览基本的docker-compose文件,使用docker提供程序公开简单的服务.
这也将用作其他docker-compose指南的起点.

Setup

  • 编辑具有以下内容docker-compose.yml文件:
version: "3.3"

services:

  traefik:
    image: "traefik:v2.0.0-rc3"
    container_name: "traefik"
    command:
      #- "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

  whoami:
    image: "containous/whoami"
    container_name: "simple-service"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami.rule=Host(`whoami.localhost`)"
      - "traefik.http.routers.whoami.entrypoints=web"
  • whoami服务的traefik.http.routers.whoami.rule标签中,用您自己的域替换whoami.localhost .
  • 在创建前一个文件的文件夹中运行docker-compose up -d .
  • 请稍等片刻,然后访问http://your_own_domain以确认一切正常. 您应该看到whoami服务的输出. 类似于:

    Hostname: d7f919e54651
    IP: 127.0.0.1
    IP: 192.168.64.2
    GET / HTTP/1.1
    Host: whoami.localhost
    User-Agent: curl/7.52.1
    Accept: */*
    Accept-Encoding: gzip
    X-Forwarded-For: 192.168.64.1
    X-Forwarded-Host: whoami.localhost
    X-Forwarded-Port: 80
    X-Forwarded-Proto: http
    X-Forwarded-Server: 7f0c797dbc51
    X-Real-Ip: 192.168.64.1

Details

  • 作为示例,我们使用了whoami (一个微型的Go服务器,该服务器打印os信息和HTTP请求以输出),用于定义我们的simple-service容器.

  • 我们定义了一个入口点,以及docker-compose中匹配端口的暴露,这基本上使我们可以"打开并接受" HTTP流量:

command:
  # Traefik will listen to incoming request on the port 80 (HTTP)
  - "--entrypoints.web.address=:80"

ports:
  - "80:80"
  • 我们公开了Traefik API,以便能够根据需要检查配置:
command:
  # Traefik will listen on port 8080 by default for API request.
  - "--api.insecure=true"

ports:
  - "8080:8080"

Note

如果在远程服务器上工作,则可以使用以下命令显示配置(需要curljq ):

curl -s 127.0.0.1:8080/api/rawdata | jq .
  • 我们允许Traefik从Docker收集配置:
traefik:
  command:
    # Enabling docker provider
    - "--providers.docker=true"
    # Do not expose containers unless explicitly told so
    - "--providers.docker.exposedbydefault=false"
  volumes:
    - "/var/run/docker.sock:/var/run/docker.sock:ro"

whoami:
  labels:
    # Explicitly tell Traefik to expose this container
    - "traefik.enable=true"
    # The domain the service will respond to
    - "traefik.http.routers.whoami.rule=Host(`whoami.localhost`)"
    # Allow request only from the predefined entry point named "web"
    - "traefik.http.routers.whoami.entrypoints=web"