什么是Matrix

Martix完全开源免费的通信协议

Martix是用于安全实时通信的去中心化端到端加密通信协议,可以保护您的隐私和通信自由。

Martix通过端到端加密来保护您的通信安全,可确保消息在发送方和接收方之间加密,中间服务器无法访问消息内容。Matrix 采用了分散式架构,没有单一的中央服务器,而是由多个独立的服务器通过联邦组成网络。

Martix支持去中心化端到端加密通信、WebRTC语音,视频通话、消息已读,输入状态提示、群组聊天等。

环境依赖

安装Matrix前请确保你的系统环境符合以下要求

  • 操作系统:Linux
  • CPU 指令架构:x86_64, arm64
  • CPU 指令架构:x86_64 架构需要支持 ssse3 指令集
  • 软件依赖:Docker 20.10.14 版本以上
  • 软件依赖:Docker Compose 2.0.0 版本以上
  • 最低资源需求:1 核 CPU / 1 GB 内存 / 5 GB 磁盘

可以根据以下命令来查看相关信息

1
2
3
4
5
6
7
8
uname -m                                    # 查看指令架构
cat /proc/cpuinfo| grep "processor" # 查看 CPU 信息
lscpu | grep ssse3 # 确认 CPU 是否支持 ssse3 指令集
docker version # 查看 Docker 版本
docker compose version # 查看 Docker Compose 版本
docker-compose version # 查看老版本 docker-compose 版本
free -h # 查看内存信息
df -h # 查看磁盘信息

安装前准备

安装前,请先想好你的服务端域名和客户端域名(如果你有指定客户端域名的需求)

在本篇教程中:

  • 服务端域名:matrix.example.com
  • 客户端域名:matrix-client.example.com

安装Matrix

安装前,请确保全程在root用户下安装,否则可能安装失败

示例仓库:

1
https://github.com/sweetsky123/matrix-docker
1
https://cnb.cool/hslzz/matrix-docker

创建目录

1
mkdir /data/synapse

创建Docker Compose编排脚本

自动下载

下载docker-compose.yml

1
cd && cd /data/synapse && wget https://github.com/sweetsky123/matrix-docker/releases/download/Release/docker-compose.yml

备用链接

1
cd && cd /data/synapse && wget https://cnb.cool/hslzz/matrix-docker/-/releases/download/lastest/docker-compose.yml

手动创建

在/data/synapse文件夹下创建docker-compose.yml

1
cd && cd /data/synapse && touch "docker-compose.yml"

使用文本编辑器打开 docer-compose.yml 文件,写入下方的内容

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
29
30
31
32
33
34
35
36
37
38
39
40
41
version: '3'
services:
# Matrix容器
matrix-synapse:
# 镜像地址
image: "matrixdotorg/synapse:latest"
# 容器名称
container_name: "matrix-synapse"
# 异常停止自动重启
restart: unless-stopped
ports:
# 端口转发
- ${MARTRIX_PORT:?error message}:8008
volumes:
- "./data:/data"
environment:
VIRTUAL_HOST: "${SERVICE_URL:?error message}"
VIRTUAL_PORT: 8008
LETSENCRYPT_HOST: "${SERVICE_URL:?error message}"
SYNAPSE_SERVER_NAME: "${SERVICE_URL:?error message}"
SYNAPSE_REPORT_STATS: "yes"
depends_on:
- matrix-pg

# Postgres数据库
matrix-pg:
# 镜像地址
image: postgres:latest
# 容器名称
container_name: matrix-pg
environment:
# 管理员密码
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?error message} # postgres管理员密码
volumes:
# 持久化数据放置目录
- ./pgdata:/var/lib/postgresql/data
# 脚本目录
- ./init:/docker-entrypoint-initdb.d
# 异常停止自动重启
restart: unless-stopped

配置compose环境变量

使用下方的命令进入Matrix安装目录,并创建.env文件

1
cd && cd /data/synapse && touch ".env"

使用文本编辑器打开 .env 文件,写入下方的内容,POSTGRES的密码需自定义

1
2
3
MARTRIX_PORT=10086
SERVICE_URL=matrix.example.com
POSTGRES_PASSWORD=NZ5yZLd5Ntxt3jXYUCCm

推荐的随机密码生成器:安全、强大的密码生成器 | 1Password

配置文件的格式说明如下:

  • MARTRIX_PORT:Martix容器的对外端口,请修改为1-65535之内的任意数字
  • SERVICE_URL:服务端域名,如matrix.example.com
  • POSTGRES_PASSWORD:Martix所需数据库的初始化密码,请随机生成一个

配置数据库创建脚本

使用下方的命令创建/init文件夹,并创建matrix.sql文件

1
cd && mkdir /data/synapse/init && cd /data/synapse/init && touch "matrix.sql"

使用文本编辑器打开 matrix.sql 文件,写入下方的内容

POSTGRES的密码需自行设置,需与.env文件中设置的相同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-- 创建matrix用户并设置密码
CREATE USER matrix WITH PASSWORD 'NZ5yZLd5Ntxt3jXYUCCm'; -- 记得要改成你在.env文件中设置的数据库密码

-- 创建使用C排序规则的matrix数据库
CREATE DATABASE matrix
WITH
OWNER = matrix
ENCODING = 'UTF8'
LC_COLLATE = 'C'
LC_CTYPE = 'C'
TEMPLATE = template0; -- 使用纯净模板,避免继承默认设置

-- 授予所有权限
GRANT ALL PRIVILEGES ON DATABASE matrix TO matrix;

生成配置文件

请将第三行的matrix.example.com改为你的服务端域名

1
2
3
4
5
sudo docker run -it --rm \
-v /data/synapse/data:/data \
-e SYNAPSE_SERVER_NAME=matrix.example.com \
-e SYNAPSE_REPORT_STATS=yes \
matrixdotorg/synapse:latest generate

执行完后,你的目录结构应为如下,若不同请检查是否有遗漏步骤

1
2
3
4
5
6
7
8
9
synapse
├── data
├── homeserver.yaml # 家服务器配置文件
├── matrix.example.com.log.config # 日志文件
└── matrix.example.com.signing.key # 服务端密钥
├── init
└── matrix.sql # 创建数据库命令
├── .env # compose环境变量文件
└── docker-compose.yml # Docker Compose编排脚本

此时,你的默认homeserver.yaml服务端配置文件应为如下,

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
29
30
31
32
33
34
35
36
37
# Configuration file for Synapse.
#
# This is a YAML file: see [1] for a quick introduction. Note in particular
# that *indentation is important*: all the elements of a list or dictionary
# should have the same indentation.
#
# [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
#
# For more information on how to configure Synapse, including a complete accounting of
# each option, go to docs/usage/configuration/config_documentation.md or
# https://element-hq.github.io/synapse/latest/usage/configuration/config_documentation.html
server_name: "matrix.example.com" # 服务器域名
pid_file: /data/homeserver.pid # 协议类型(http/manhole/metrics)
listeners: # 服务监听配置
- port: 8008 # 监听端口
tls: false # 是否启用https
type: http # 协议类型
x_forwarded: true # 启用 X-Forwarded-For 头
resources: # 资源类型
- names: [client, federation] # 资源列表
compress: false # 启用 gzip 压缩
database: # 数据库配置
name: sqlite3 # 默认使用sqllite数据库
args:
database: /data/homeserver.db # 数据库存储路径
log_config: "/data/matrix.example.com.log.config" # 日志配置文件路径
media_store_path: /data/media_store
registration_shared_secret: "VH:0I@rI9BCNI~TCO,.YE~+5k#fJG3m0H5&6KUbh=9.Cr*YbQB"
report_stats: true
macaroon_secret_key: "~_wKxePWW&I@,xlWG6j:&lv8#1.io#:Ru:kjqL8T;J6.esRvkS"
form_secret: "34;:CLfGEX-1qV9=XsJKe:V-OFKn+@JhxyIVGcaTkCoXIKN~cK"
signing_key_path: "/data/matrix.example.com.signing.key"
trusted_key_servers:
- server_name: "matrix.org"


# vim:ft=yaml

修改服务端配置文件

    1. 注释原database块、配置Postgres数据库,修改后如下:

你可选择配置连接池最小/最大连接数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
database:
name: psycopg2 # 使用 PostgreSQL 驱动
args:
user: matrix # 数据库用户
password: NZ5yZLd5Ntxt3jXYUCCm # 数据库密码
dbname: matrix # 数据库名
host: matrix-pg # 数据库容器名
# cp_min: 5 # 连接池最小连接数
# cp_max: 10 # 连接池最大连接数


# database:
# name: sqlite3
# args:
# database: /data/homeserver.db
    1. 新增自动生成.well-known文件配置,新增客户端访问地址配置
1
2
3
4
# 自动生成 .well-known 文件
serve_server_wellknown: true
# 客户端访问地址
public_baseurl: https://matrix.example.com
    1. Debug测试:添加开放注册、注册无需验证配置(生产环境请关闭、注释或删除后重启容器即可)
1
2
3
4
# 为新用户启用注册
enable_registration: true
# 无需电子邮件或 recaptcha 验证即可注册(其实不推荐)
enable_registration_without_verification: true

若要添加下方可选配置,请完成上方配置后测试是否可以正常使用再进行配置

    1. 可选)配置邮件通知
1
2
3
4
5
6
7
8
9
10
email:
smtp_host: smtp.example.com # SMTP 服务器
smtp_port: 465 # SMTP 端口
smtp_user: matrix@example.com # SMTP 用户
smtp_pass: Mailpassword # SMTP 密码
force_tls: true # 强制 TLS
require_transport_security: true # 要求传输安全
enable_tls: true # 启用 TLS
notif_from: "Matrix <service@example.com>" # 通知来源
enable_notifs: true # 启用通知
    1. (可选)优化性能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 事件缓存大小
event_cache_size: 10K
# 缓存配置
caches:
global_factor: 0.5 # 全局缓存系数
per_cache_factors: # 单个缓存系数
get_users_who_share_room_with_user: 2.0
expire_caches: true # 启用缓存过期
cache_entry_ttl: 30m # 缓存条目存活时间
# 垃圾回收
gc_thresholds: [700, 10, 10] # GC 阈值
gc_min_interval: [1s, 10s, 30s] # GC 最小间隔
# 性能优化
max_event_delay_duration: 24h # 最大事件延迟
filter_timeline_limit: 100 # 时间线事件限制
    1. (可选)安全配置
1
2
3
4
5
ip_range_blacklist:                           # 禁止访问的 IP 段
- "127.0.0.0/8"
- "10.0.0.0/8"
ip_range_whitelist: # 允许访问的 IP 段(覆盖黑名单)
- "192.168.1.0/24"
    1. (可选)联邦配置
1
2
3
4
5
6
7
# 联邦白名单
federation_domain_whitelist:
- example.com
- another.com
# 联邦证书验证
federation_verify_certificates: true # 验证联邦证书
federation_client_minimum_tls_version: "1.2" # 最低 TLS 版本
    1. 保留策略
1
2
3
4
5
6
7
8
9
10
retention:
enabled: true # 启用保留策略
default_policy: # 默认策略
min_lifetime: 1d
max_lifetime: 1y
allowed_lifetime_min: 1d # 最小允许保留时间
allowed_lifetime_max: 1y # 最大允许保留时间
purge_jobs: # 清理任务
- shortest_max_lifetime: 3d
interval: 12h
    1. 其他配置
1
2
3
4
5
6
7
8
9
10
# 用户类型
user_types:
default_user_type: null
extra_user_types: []
# 限制配置
limit_usage_by_mau: false # 限制月活用户
max_mau_value: 0 # 最大月活用户数
# 模板配置
templates:
custom_template_directory: /path/to/templates # 自定义模板目录

我自用的最终homeserver.yaml文件如下(关键部分脱敏)

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# Configuration file for Synapse.
#
# This is a YAML file: see [1] for a quick introduction. Note in particular
# that *indentation is important*: all the elements of a list or dictionary
# should have the same indentation.
#
# [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
#
# For more information on how to configure Synapse, including a complete accounting of
# each option, go to docs/usage/configuration/config_documentation.md or
# https://element-hq.github.io/synapse/latest/usage/configuration/config_documentation.html
# 服务器域名
server_name: "matrix.example.com"

# 自动生成 .well-known 文件
serve_server_wellknown: true

# 客户端访问地址
public_baseurl: https://matrix.example.com

# PID 文件路径
pid_file: /data/homeserver.pid

# 服务监听配置
listeners:
# 监听端口
- port: 8008
# 是否启用https
tls: false
# 协议类型
type: http
# 启用 X-Forwarded-For 头
x_forwarded: true
# 资源类型
resources:
# 资源列表
- names: [client, federation]
# 启用 gzip 压缩
compress: true
database:
name: psycopg2 # 使用 PostgreSQL 驱动
args:
user: matrix # 数据库用户
password: zR7Kd5AKb3BE7Y5k # 数据库密码
dbname: matrix # 数据库名
host: matrix-pg # 数据库容器名
# cp_min: 5 # 连接池最小连接数
# cp_max: 10 # 连接池最大连接数
log_config: "/data/matrix.example.com.log.config" # 日志配置文件路径
media_store_path: /data/media_store
registration_shared_secret: "VH:0I@rI9BCNI~TCO,.YE~+5k#fJG3m0H5&6KUbh=9.Cr*YbQB"
report_stats: true
macaroon_secret_key: "~_wKxePWW&I@,xlWG6j:&lv8#1.io#:Ru:kjqL8T;J6.esRvkS"
form_secret: "34;:CLfGEX-1qV9=XsJKe:V-OFKn+@JhxyIVGcaTkCoXIKN~cK"
signing_key_path: "/data/matrix.example.com.signing.key"
trusted_key_servers:
- server_name: "matrix.org"


enable_registration: true
enable_registration_without_verification: true



# 事件缓存大小
event_cache_size: 10K
# 缓存配置
caches:
global_factor: 0.5 # 全局缓存系数
per_cache_factors: # 单个缓存系数
get_users_who_share_room_with_user: 2.0
expire_caches: true # 启用缓存过期
cache_entry_ttl: 60m # 缓存条目存活时间
# 垃圾回收
gc_thresholds: [700, 10, 10] # GC 阈值
gc_min_interval: [1s, 10s, 30s] # GC 最小间隔
# 性能优化
max_event_delay_duration: 24h # 最大事件延迟
filter_timeline_limit: 100 # 时间线事件限制



email:
smtp_host: smtp.example.com # SMTP 服务器
smtp_port: 465 # SMTP 端口
smtp_user: matrix@example.com # SMTP 用户
smtp_pass: Mailpassword # SMTP 密码
force_tls: true # 强制 TLS
require_transport_security: true # 要求传输安全
enable_tls: true # 启用 TLS
notif_from: "Matrix <service@example.com>" # 通知来源
enable_notifs: true # 启用通知


# 服务器提示配置
# server_notices:
# enabled: true # 启用服务器提示功能
# 可选:配置发送提示的机器人账号(需提前注册)
# sender_localpart: "bot"
# 可选:提示的默认房间配置
# room_name: "Server Notices"
# room_alias: "@bot:matrix.hslzz.cn"
# 可选:提示消息的模板
# message_type: "m.text"
# vim:ft=yaml

构建Docker容器

现在万事大吉,可以开始构建你的Docker容器了

1
cd && cd /data/synapse && docker compose up -d

配置反向代理进行访问测试

  • 上游服务器:http://127.0.0.1:你设置的端口号http://Synapse容器ip:8080
  • 域名:你的服务端域名,在本篇文章是matrix.example.com

配置好反向代理进行访问,若为此页面则为安装成功

正常访问示例

添加第一个管理员用户

请将命令最后的用户名和密码替换成你想添加的用户名和密码

1
docker exec -it matrix-synapse register_new_matrix_user http://localhost:8008 -c /data/homeserver.yaml -a -u 用户名 -p 密码

修改Android端

在Google Play中下载Element

https://play.google.com/store/apps/details?id=im.vector.app

或下载我在Google Play安装后提取的安装包:

1
https://cnb.cool/hslzz/matrix-docker/-/releases/download/lastest/Element_1.6.42.apk
1
https://github.com/sweetsky123/matrix-docker/releases/download/Release/Element_1.6.42.apk

默认的Element软件启动后点击登录或注册,会先连接matrix.org,且在连接过程中无法点击任何东西。

由于众所周知的原因,中国大陆网络无法连接matrix.org,导致无法使用Element作为Android Matrix客户端。

因此,我们需要对它的APK进行反编译以修改连接地址

推荐我自用的MT管理器版本

1
https:/cnb.cool/hslzz/matrix-docker/-/releases/download/lastest/MTManager_2.18.2.apk
1
https://github.com/sweetsky123/matrix-docker/releases/download/Release/MTManager_2.18.2.apk
  1. 点击APK安装包后,进入查看

  2. 点击任意.dex文件后,点击第一个选项Dex编辑器++

  3. 全选所有dex文件,点击确定

  4. 搜索matrix.org

  5. matrix.org替换为你的域名:

  • matrix.org替换为你的服务端域名,如matrix.example.com
  • matrix-client.matrix.org替换为你的客户端域名,如matrix-client.example.com

然后点击右上角的锤子进行编译,编译后退出,按提示保存即可。