Making Consul and Containerized .Net Core Applications Get Along
[TOC]
## .Net项目代码实现
### 项目添加环境变量
在``` launchSettings.json```配置文件中``` environmentVariables```的子项中添加以下变量:
```json
"CONSUL_PORT_8500_TCP_ADDR": "127.0.0.1",
"CONSUL_PORT_8500_TCP_PORT": "8500"
```
有几个 ``` environmentVariables ```就添加几遍,这样在任何模式调试的时候,都是默认连接127.0.0.1:8500的Consul API。
**注**:“CONSUL_PORT_8500_TCP_ADDR”、“CONSUL_PORT_8500_TCP_PORT”是Consul容器化运行之后的环境变量名称。
### ConsulClient实例化
``` c#
string ConsulUrl = $"http://{Environment.GetEnvironmentVariable("CONSUL_PORT_8500_TCP_ADDR")}:{Environment.GetEnvironmentVariable("CONSUL_PORT_8500_TCP_PORT")}";
ConsulClient consulClient = new ConsulClient(new Action<ConsulClientConfiguration>(e => e.Address = new Uri( ConsulUrl)));
```
## 容器化启动项目
### Consul在Docker容器中运行
#### 创建Volume卷
```bash
docker volume create consul-vol
```
#### 启动Consul容器
``` bash
docker run -h node1 --name consul -d -v consul-vol:/consul/data --restart=always \
-p 8300:8300 -p 8301:8301 -p 8301:8301/udp -p 8302:8302 -p 8302:8302/udp -p 8400:8400 -p 8500:8500 \
consul:1.3.0 agent -server -bootstrap-expect 1 -client=0.0.0.0 -bind=0.0.0.0 -ui
```
#### 启动.Net项目容器
```bash
docker run -d -p 8080:8080 --rm --name webapi --link consul:consul webapi:0.1
```
### Consul在宿主机上运行
#### 启动Consul
``` bash
consul agent -server -bootstrap-expect 1 -data-dir ~/consuldata -client=192.168.3.8 -bind=127.0.0.1 -ui &
```
#### 启动.Net项目容器
``` bash
docker run -d -p 8080:8080 --rm --name webapi -e CONSUL_PORT_8500_TCP_ADDR=192.168.3.8 -e CONSUL_PORT_8500_TCP_PORT=8500 webapi:0.1
```