docker-compose.yml

version: "3"
services:
  nacos:
    image: nacos/nacos-server:v2.1.1
    environment:
    - MODE=standalone
    ports:
      - 8848:8848
  apisix:
    image: apache/apisix:2.15.0-alpine
    restart: always
    volumes:
      - ./conf/apisix.yaml:/usr/local/apisix/conf/config.yaml:ro
    depends_on:
      - etcd
    ports:
      - 9080:9080/tcp
      - 9091:9091/tcp
      - 9443:9443/tcp
      - 9092:9092/tcp
  etcd:
    image: bitnami/etcd:3.4.15
    restart: always
    volumes:
      - ./data/etcd:/bitnami/etcd
    environment:
      - ETCD_ENABLE_V2=true
      - ALLOW_NONE_AUTHENTICATION=yes
      - ETCD_ADVERTISE_CLIENT_URLS=http://0.0.0.0:2379
      - ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379
    ports:
      - 2379:2379/tcp
  demo:
    image: demo:v1
    restart: always
    ports:
      - "8080:8080"

添加APISIX配置conf/config.yaml:

discovery:
  nacos:
    host:
      - "http://nacos:8848"

注册Nacos服务实例:

{
    "name": "DEFAULT_GROUP@@demo",
    "groupName": "DEFAULT_GROUP",
    "clusters": "",
    "cacheMillis": 10000,
    "hosts": [
        {
            "instanceId": "demo#8080#DEFAULT#DEFAULT_GROUP@@demo",
            "ip": "demo",
            "port": 8080,
            "weight": 1.0,
            "healthy": true,
            "enabled": true,
            "ephemeral": false,
            "clusterName": "DEFAULT",
            "serviceName": "DEFAULT_GROUP@@demo",
            "metadata": {},
            "instanceHeartBeatTimeOut": 15000,
            "ipDeleteTimeout": 30000,
            "instanceHeartBeatInterval": 5000,
            "instanceIdGenerator": "simple"
        }
    ],
    "lastRefTime": 1664734273176,
    "checksum": "",
    "allIPs": false,
    "reachProtectionThreshold": false,
    "valid": true
}

注册实例时也碰上nacos中raft的leader无法选举导致注册失败的问题,重启nacos容器即可。

以nacos服务发现作为上游设置APISIX的路由后,访问结果:

<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>openresty</center>
</body>
</html>

进到APISIX查看错误日志 '/usr/local/apisix/logs/error.log':

[error] 46#46: *6112951 [lua] balancer.lua:382: run(): failed to set server peer [demo:8080] err: no host allowed while connecting to upstream, client: 27.153.187.50, server: _, request: "GET /nacos/admin HTTP/1.1", host: "43.139.5.157:9080"

说明在nacos中注册实例ip为demo不行,必须写实际ip地址,且还要重写请求路径,否则请求到demo的路径为原请求路径。同时上游的配置需加上:"pass_host": "node"

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐