1. 程式人生 > >Making Consul and Containerized .Net Core Applications Get Along

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
```