简介

Nacos(Dynamic Naming and Configuration Service)是阿里巴巴开源的一款动态服务发现、配置管理和服务管理平台。本文将介绍如何使用 Docker 容器化安装 Nacos 以及如何配置 Nacos 的代理。

前提条件

  • 已安装 Docker 和 Docker Compose
  • 基本的 Docker 和 Docker Compose 知识

容器化安装 Nacos

1. 创建 Docker Compose 文件

首先,在你的项目目录中创建一个名为 docker-compose.yml 的文件,并添加以下内容:

version: '3'

services:
  nacos:
    image: nacos/nacos-server:1.4.2
    container_name: nacos
    restart: always
    ports:
      - "8848:8848"
    volumes:
      - ./data:/home/nacos/data  # 数据目录挂载
    environment:
      - MODE=standalone
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

2. 启动 Nacos

在项目目录中运行以下命令来启动 Nacos 服务:

docker-compose up -d
  • 1.

这将下载 Nacos 镜像并在后台启动 Nacos 容器。

3. 验证安装

Nacos 容器启动后,可以通过访问 http://localhost:8848/nacos 来验证安装。默认的登录账号和密码均为 nacos。

配置 Nacos 代理

为了提高 Nacos 的可用性和安全性,我们可以配置一个反向代理,如 Nginx。

1. 安装 Nginx

首先,确保你已经安装了 Nginx。如果没有,可以通过以下命令安装:

# Ubuntu/Debian
sudo apt-get update
sudo apt-get install nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2. 配置 Nginx

创建或修改 Nginx 配置文件(通常位于/etc/nginx/sites-available/default/etc/nginx/conf.d/default.conf),添加以下内容:

upstream nacos {
    server 127.0.0.1:8848; # Nacos 运行的 IP 和端口
}

server {
    listen 80;
    server_name your_domain;
    rewrite ^(.*)$ https://$host$1;
    location / {
        index index.html index.htm;
    }
}

server {
     listen 443 ssl;
     server_name your_domain;

     ssl_certificate ssl/<>.pem;
     ssl_certificate_key ssl/<>.key;

     location / {
        proxy_pass http://nacos/; # 确保这里的 Nacos 上游不带端号
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

将 your_domain_or_IP 替换为你的实际域名或 IP 地址。

3. 重启 Nginx

配置完成后,重启 Nginx 以使配置生效:

sudo systemctl restart nginx
  • 1.

4. 验证代理配置

现在,可以通过访问https://your_domain/nacos来验证 Nginx 代理是否配置成功。