podman-compose系列之ELK搭建

ELK介绍

E: 指elasticsearch用于数据落盘存储。
L: 指logstash用于聚合接收日志并将数据存入elasticsearch。
K: 指kibana,用于界面展示和查询。

docker-compose增加elasticsearch、logstash和kibana三大组件

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
version: '3.9'
networks:
component: {}
services:
elasticsearch:
image: bitnami/elasticsearch:latest
container_name: elasticsearch
env_file:
- ./environment/elasticsearch.env
networks:
- component
ports:
- 9200:9200
- 9300:9300
volumes:
- ./elasticsearch/data:/bitnami/elasticsearch/data
- ./elasticsearch/plugins:/bitnami/elasticsearch/plugins
kibana:
image: bitnami/kibana:latest
container_name: kibana
env_file:
- ./environment/kibana.env
networks:
- component
extra_hosts:
- "elasticsearch:192.168.1.1"
ports:
- 5601:5601
logstash:
image: bitnami/logstash:latest
container_name: logstash
env_file:
- ./environment/logstash.env
networks:
- component
ports:
- 10000:10000
- 10001:10001
- 10002:10002
- 9600:9600
volumes:
- ./logstash/pipeline/:/opt/bitnami/logstash/pipeline/
- ./logstash/data/:/opt/bitnami/logstash/data/

注意:将elasticsearch、environment、logstash三个目录设置为1001。(chown -R 1001:1001 elasticsearch environment logstash)

三大组件环境变量设置

./environment/elasticsearch.env

1
2
3
4
TZ=Asia/Shanghai
discovery.type=single-node
ELASTICSEARCH_ENABLE_REST_TLS=false
ES_JAVA_OPTS=-Xms512m -Xmx512m

./environment/kibana.env

1

./environment/logstash.env

1
TZ=Asia/Shanghai

logstash采集配置

./logstash/config/logstash.yml指定pipeline配置文件目录

1
path.config: /usr/share/logstash/pipeline

./logstash/pipeline/logstash.conf 配置采集规则

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
input {
tcp {
mode => "server"
host => "0.0.0.0"
port => 1000
tags => ["prod"]
codec => json_lines
}
tcp {
mode => "server"
host => "0.0.0.0"
port => 1001
tags => ["dev"]
codec => json_lines
}
tcp {
mode => "server"
host => "0.0.0.0"
port => 1002
tags => ["test"]
codec => json_lines
}
}

output {
if "prod" in [tags] {
elasticsearch {
hosts => ["http://host.containers.internal:9200"]
index => "logstash-prod"
codec => "json"
}
} else if "dev" in [tags] {
elasticsearch {
hosts => ["http://host.containers.internal:9200"]
index => "logstash-dev"
codec => "json"
}
} else if "test" in [tags] {
elasticsearch {
hosts => ["http://host.containers.internal:9200"]
index => "logstash-test"
codec => "json"
}
}

stdout {
codec => rubydebug
}
}

访问地址

kibana ==> http://localhost:5601

elasticsearch ==> http://localhost:9200

SpringBoot通过logstash-logback-encoder发送日志数据到logstash

pom.xml增加logstash-logback-encoder依赖

1
2
3
4
5
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>7.2</version>
</dependency>

logback-spring.xml增加appender和logger (以控制台输出info及以上级别日志,logstash收集error级别日志为例)

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
<appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<!--logstash的服务地址和端口,可以实际情况设置-->
<destination>host-logstash.com:1000</destination>
<!-- 日志级别过滤 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<!-- 日志输出编码 -->
<encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
<includeMdc>false</includeMdc>
<includeContext>false</includeContext>
<provider class="net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider">
<pattern>
{"app":"${APP_NAME}","level":"%level","traceId":"%X{X-Request-Id}","position":"%logger:%L","message":"%msg"}
</pattern>
</provider>
</encoder>
</appender>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss:SSS}][%thread][%logger:%L][%level][%X{X-Request-Id}] - %msg%n</pattern>
<charset class="java.nio.charset.Charset">UTF-8</charset>
</encoder>
</appender>

<root level="DEBUG">
<appender-ref ref="STDOUT" />
<appender-ref ref="LOGSTASH" />
</root>

观点仅代表自己,期待你的留言。

Podman容器开机自启动

ROOT用户启动容器

  1. 启动一个容器
    1
    # podman run -d --name web httpd
  2. 查看该容器
    1
    # podman ps
  3. 每次都启动新容器方式创建servcie //–new参数,每次启动都删除旧容器,启动一个新容器
    1
    # podman generate systemd -n --new -f web
  4. 将service文件保存在/etc/systemd/system/
    1
    # mv container-web.service /etc/systemd/system/
  5. 刷新配置文件,让其生效
    1
    # systemctl daemon-reload
  6. 修改selinux
    1
    # cat config |grep SELINUX=disabled
  7. 设置容器开机自启,并且现在启动
    1
    # systemctl enable --now /etc/systemd/system/container-web.service
  8. 测试,重启虚拟机
    1
    # reboot
  9. 查看容器是否在运行,并查看container-web.service是否开机自启和运行
    1
    2
    # systemctl status container-web.service
    # podman ps

rootless模式启动容器

  1. 创建~/.config/systemd/user/目录来存储unit文件
    1
    # mkdir -p ~/.config/systemd/user/
  2. 查看该容器
    1
    # podman ps
  3. 每次都启动新容器方式创建servcie //–new参数,每次启动都删除旧容器,启动一个新容器
    1
    # podman generate systemd -n --new -f web
  4. 将service文件保存在~/.config/systemd/user/
    1
    # mv container-web.service ~/.config/systemd/user/
  5. 刷新配置文件,让其生效
    1
    # systemctl --user daemon-reload
  6. 修改selinux
    1
    # cat config |grep SELINUX=disabled
  7. 设置容器开机自启,并且现在启动
    1
    # systemctl --user enable --now ~/.config/systemd/user/container-web.service
  8. 测试启动容器
    1
    # systemctl --user restart container-web.service
  9. 查看容器是否在运行,并查看container-web.service是否开机自启和运行
    1
    2
    # systemctl --user status container-web.service
    # podman ps

注意: systemd使用systemctl命令管理这些服务当用户服务类型为非根用户时,通过文本或图形控制台或使用SSH打开第一个会话时, 该服务将自动启动。当关闭最后一次会话时,服务将停止。
这种行为与系统服务不同,系统服务在系统启动时启动,在系统关闭时停止。但也可以更改此默认行为,通过运行loginctl enable-linger命令强制service在服务器启动时启动并在关闭时停止。
逆向操作,请使用loginctl disable-linger命令。查看当前状态,使用loginctl show-user username命令。


观点仅代表自己,期待你的留言。

Docker与Podman在容器内获取宿主机网络IP

Docker使用host-getway

docker需要在创建容器时加入桥接地址为外部host,容器内则可通过桥接地址来访问宿主机的网络。

  • docker创建时增加 --add-host <hostname>:<ip>,如:--add-host host.docker.internal:host-gateway
  • docker-compose.yml中增加
    1
    2
    extra_hosts:
    - "host.docker.internal:host-gateway"

Podman容器

podman在创建容器时会在容器中/etc/hosts文件内加入一个宿主机的host,使用host.containers.internal由可以访问到宿主机的网络


观点仅代表自己,期待你的留言。

Docker与Podman日志大小设置

Docker限制容器日志大小

日志存储路径:

1
2
3
4
5
6
7
8
9
10
vi /etc/docker/daemon.json
以限制50mb为例,配置以下内容

{
"log-driver": "json-file",
"log-opts": {
"max-size": "50m",
"max-file": 3
}
}

注意:设置的日志大小,只对新建的容器有效。已存在的容器不会生效,需要重建才可以.

Podman限制容器日志大小

root用户下启动的容器

日志存储路径: /var/lib/containers/storage/overlay-containers/[CONTAINER_ID]/userdata/ctr.log

1
2
3
4
5
6
vi /etc/containers/containers.conf
以限制10mb为例,配置以下内容

[containers]
log_size_max=10485760

rootless下启动的容器

日志存储路径: $HOME/.local/share/containers/storage/overlay-containers/[CONTAINER_ID]/userdata/log/ctr.log

1
2
3
4
5
$HOME/.config/containers/containers.conf
以限制10mb为例,配置以下内容

[containers]
log_size_max=10485760

观点仅代表自己,期待你的留言。

MySQL备份与恢复

MySQL备份

方案一:将mysql整个数据目录备份,默认在/var/lib/mysql下,可通过my.conf指定
方案二:通过mysqldump命名备份成sql

通过mysqldump备份成sql

1
wujianjun@wujianjun-work:~$ mysqldump -uroot -p --default-character-set=utf8 --set-charset=false --hex-blob --databases db_basic db_boss --result-file=service_module_db_init.sql

ps: 如果需要替换则可通过sed正则替换

1
2
wujianjun@wujianjun-work:~$ sed -i "s/原内容/新内容/g" service_module_db_init.sql
wujianjun@wujianjun-work:~$ find . -type f -name "app" -exec sh {} restart \; #批量执行shell

通过mysql命令恢复备份文件

1
wujianjun@wujianjun-work:~$ mysql -uroot -p --default-character-set=utf8 < service_module_db_init.sql

忘记MySQL的root密码后修改密码

1
2
3
4
5
6
7
8
wujianjun@wujianjun-work:~$ service mysql stop
wujianjun@wujianjun-work:~$ mysqld --console --skip-grant-tables --shared-memory
wujianjun@wujianjun-work:~$ mysql -u root -p
mysql> use mysql;
mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '新密码';
mysql> flush privileges;
mysql> exit
wujianjun@wujianjun-work:~$ service mysql start

观点仅代表自己,期待你的留言。

Linux下硬盘的一些操作

Linux环境信息

1
2
3
4
5
6
7
8
9
10
11
12
13
wujianjun@wujianjun-work:~$ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy

同一硬盘逻辑分区扩容

1
2
3
4
5
6
wujianjun@wujianjun-work:~$ fdisk -l #查看系统硬盘信息
wujianjun@wujianjun-work:~$ lsblk #查看硬盘分区及容量情况
wujianjun@wujianjun-work:~$ df -hT #查看挂载情况
wujianjun@wujianjun-work:~$ lvdisplay #查看逻辑分区情况
wujianjun@wujianjun-work:~$ lvextend -L +1643.2G /dev/ubuntu-vg/ubuntu-lv #/dev/ubuntu-vg/ubuntu-lv为lvdisplay中展示的LV Path
wujianjun@wujianjun-work:~$ resize2fs /dev/ubuntu-vg/ubuntu-lv #重新加载逻辑卷

删除硬盘分区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wujianjun@wujianjun-work:~$ lsblk #查看硬盘分区及容量情况
root@gigatech-linux:~# fdisk /dev/sdb #/dev/sdb为fdisk -l中的硬盘名
Welcome to fdisk (util-linux 2.37.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): d
Selected partition 1
Partition 1 has been deleted.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

增加硬盘分区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
wujianjun@wujianjun-work:~$ lsblk #查看硬盘分区及容量情况
wujianjun@wujianjun-work:~$ fdisk /dev/sdb
Welcome to fdisk (util-linux 2.37.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Command (m for help): n
Partition type
p primary (0 primary, 0 extended, 4 free)
e extended (container for logical partitions)
Select (default p): e
Partition number (1-4, default 1):
First sector (2048-3907029167, default 2048):
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-3907029167, default 3907029167):

Created a new partition 1 of type 'Extended' and of size 1.8 TiB.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.
wujianjun@wujianjun-work:~$ mkfs -t ext4 /dev/sdb1 #对新区进行格式化

根分区扩容加装硬盘(当根分区为lvm时可行)

1
2
3
4
5
wujianjun@wujianjun-work:~$ vgdisplay -v #查看卷分组
wujianjun@wujianjun-work:~$ pvcreate /dev/sdb1 #创建物理卷,pvdisplay查看创建结果
wujianjun@wujianjun-work:~$ vgextend ubuntu-vg /dev/sdb1 #将物理卷添加到根分区所属卷分组,券分组为vgdisplay的VG Name
wujianjun@wujianjun-work:~$ lvextend -L +256G /dev/ubuntu-vg/ubuntu-lv #扩展lvm容量
wujianjun@wujianjun-work:~$ resize2fs /dev/ubuntu-vg/ubuntu-lv #重新加载逻辑卷

观点仅代表自己,期待你的留言。

OpenVPN系列三之账号密码认证

背景

基于vpn的敏感性及人员的流动性,要进一步加强访问的安全性。OpenVPN支持配置账号密码认证。

OpenVPN服务端配置修改

  1. 增加验证配置
    1
    root@wujianjun-work:~# vi /etc/openvpn/server/server.conf
    在配置文件末尾增加
    1
    2
    3
    4
    script-security 3
    auth-user-pass-verify checkpsw.sh via-env
    username-as-common-name
    client-cert-not-required
1
root@wujianjun-work:~# vi ~/client_conf/base.conf

在配置文件”auth SHA256”后增加

1
auth-user-pass

重新生成客户端ovpn文件

1
2
root@wujianjun-work:~# cd ~/client_conf/
root@wujianjun-work:~# ./make_config.sh client
  1. 增加账号验证脚本

    1
    root@wujianjun-work:~# vi /etc/openvpn/server/checkpsw.sh

    内容如下:

    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
    #!/bin/sh
    ###########################################################
    # checkpsw.sh (C) 2004 Mathias Sundman <mathias@open***.se>
    #
    # This script will authenticate Open××× users against
    # a plain text file. The passfile should simply contain
    # one row per user with the username first followed by
    # one or more space(s) or tab(s) and then the password.

    PASSFILE="/etc/openvpn/server/psw-file"
    LOG_FILE="/var/log/openvpn/openvpn-password.log"
    TIME_STAMP=`date "+%Y-%m-%d %T"`

    ###########################################################

    if [ ! -r "${PASSFILE}" ]; then
    echo "${TIME_STAMP}: Could not open password file \"${PASSFILE}\" for reading." >> ${LOG_FILE}
    exit 1
    fi

    CORRECT_PASSWORD=`awk '!/^;/&&!/^#/&&$1=="'${username}'"{print $2;exit}' ${PASSFILE}`

    if [ "${CORRECT_PASSWORD}" = "" ]; then
    echo "${TIME_STAMP}: User does not exist: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
    exit 1
    fi

    echo "${password}--${CORRECT_PASSWORD}" >> ${LOG_FILE}

    if [ "${password}" = "${CORRECT_PASSWORD}" ]; then
    echo "${TIME_STAMP}: Successful authentication: username=\"${username}\"." >> ${LOG_FILE}
    exit 0
    fi

    echo "${TIME_STAMP}: Incorrect password: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
    exit 1
  2. 增加账号配置

    1
    root@wujianjun-work:~# vi /etc/openvpn/server/checkpsw.sh

    内容如下:

    1
    2
    #account password
    test 123
  3. 重启服务

    1
    root@wujianjun-work:~# sudo systemctl restart openvpn-server@server.service

客户机再次尝试连接vpn时则会提示输入认证账号


观点仅代表自己,期待你的留言。

OpenVPN系列二之外网映射

背景

OpenVPN系列一之安装配置配置好之后,需要做以下两件事情才能让客户机正常使用

  • OpenVPN服务器1194端口映射到外网,则客户机通过外网就能连接上vpn
  • 内网服务器能访问到OpenVPN的子网内的客户机

以上两步需要在路由上进行设置

服务器环境参数

序号 设备名 IP地址 说明
1 路由器 10.84.102.1 H3C专线路由器
2 Vpn服务器 10.84.102.131 搭建20.04 LTS操作系统
3 服务器1 10.84.102.90 内网服务器

所涉及到的软件为:
OpenVPN 2.4.7(服务端)
Tunnelblick 3.8.7a(客户机软件)

OpenVPN服务器1194端口映射到外网

登录到路由器10.84.102.1进行外网映射配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
******************************************************************************
* Copyright (c) 2004-2015 Hangzhou H3C Tech. Co., Ltd. All rights reserved. *
* Without the owner's prior written consent, *
* no decompiling or reverse-engineering shall be allowed. *
******************************************************************************


Login authentication


Username:admin
Password:
<GPluslife>sys
System View: return to User View with Ctrl+Z.
# 进入外网网卡
[GPluslife]in gig0/0
[GPluslife-Ethernet0/0] nat server 15 protocol udp global current-interface 1194 inside 10.84.102.131 1194
[GPluslife-Ethernet0/0] save
[GPluslife-Ethernet0/0] quit
# 查看更改后的配置是否成功
[GPluslife]dis cur
[GPluslife]quit

映射完成后可找台外网服务器通过nmap扫描下1194端口是否开放

1
2
3
4
5
6
7
root@wujianjun-net-work:~# nmap -sU [路由器外网IP] -p 1194 -Pn
Starting Nmap 7.80 ( https://nmap.org ) at 2022-08-04 11:36 CST
Nmap scan report for xx.xx.xx.xx
Host is up.

PORT STATE SERVICE
1194/udp open|filtered openvpn

经过以上步骤,可通过client1.ovpn加载到Tunnelblick进行连接了。

注意:client1.ovpn配置中的remote后的ip为路由器的外网IP

内网服务器能访问到OpenVPN的子网内

登录到路由器10.84.102.1进行子网路由配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
******************************************************************************
* Copyright (c) 2004-2015 Hangzhou H3C Tech. Co., Ltd. All rights reserved. *
* Without the owner's prior written consent, *
* no decompiling or reverse-engineering shall be allowed. *
******************************************************************************


Login authentication


Username:admin
Password:
<GPluslife>sys
System View: return to User View with Ctrl+Z.
# 查看现有配置
[GPluslife]dis cur
[GPluslife] ip route-static 10.8.0.0 255.255.255.0 10.84.102.131
# 查看添加路由后的配置
[GPluslife]dis cur
[GPluslife] save
[GPluslife] quit

经过以上步骤,可通过内网服务器(10.84.102.90)ping客户机分配的(10.8.0.x)是否可以连通

客户机信息查看,以macOS为例

1
2
3
4
# 查看客户机的vpn所分配的内网IP地址
wujianjun@work-mbp blog % ifconfig
# 查看客户机路由表
wujianjun@work-mbp blog % netstat -nr

常见问题, 以macOS为例

  1. Tunnelblick出现write UDP: Can't assign requested address (code=49)错误
    解决方案:由于客户机路由表影响,通过在终端sudo route flush来解决

  2. 测试期间可以尝试通过以下方法来在客户机上加路由
    解决方案:
    #添加基于接口的路由
    sudo route add -host 1.1.1.1 -iface lo0
    sudo route add -net 1.1.1.0/24 -iface lo0
    #添加基于网关IP的路由
    sudo route add -net 1.1.1.0/24 192.168.1.1
    sudo route add -host 1.1.1.1 192.168.1.1
    #删除静态路由
    sudo route delete 1.1.1.0/24
    sudo route delete 1.1.1.1


观点仅代表自己,期待你的留言。

OpenVPN系列一之安装配置

背景

最近成都疫情严重,为了研发工作顺序不中断推进,方便研发人员在家也能debug程序,需要外网到内网访问通道。

最初在H3C路由器上搭建L2TP VPN通道,经测试发现macOS11能正常联通和使用,在macOS12下则能ping通但不能访问内网服务器的任何其它端口,在网络上遇到这个问题的人还不少,都没有提出有效的解决方法。

经过不断的尝试最终决定在内网服务器上通过vpn软件来构建vpn访问通道。

服务器环境参数

序号 设备名 IP地址 说明
1 路由器 10.84.102.1 H3C专线路由器
2 Vpn服务器 10.84.102.131 搭建20.04 LTS操作系统
3 服务器1 10.84.102.90 内网服务器

所涉及到的软件为:
OpenVPN 2.4.7(服务端)
Tunnelblick 3.8.7a(客户机软件)

搭建VpnServer

以下操作均在10.84.102.131上进行

安装软件

1
2
3
4
5
6
7
root@wujianjun-work:~# sudo apt update
root@wujianjun-work:~# sudo apt install openvpn easy-rsa
root@wujianjun-work:~# openvpn --version
OpenVPN 2.4.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Mar 22 2022
library versions: OpenSSL 1.1.1f 31 Mar 2020, LZO 2.10
Originally developed by James Yonan
Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>

配置并启动VpnServer

  1. OpenVPN使用TLS/SSL协议保证传输安全,它使用证书对服务器与客户端之间的传输进行加密,所以这里需要我们自己创建一个简单的CA证书,easy-rsa可以帮助我们做到这一点。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    root@wujianjun-work:~# mkdir ~/ca
    root@wujianjun-work:~# ln -s /usr/share/easy-rsa/* ~/ca/
    root@wujianjun-work:~# cd ~/ca
    root@wujianjun-work:~# sudo vi var

    打开var文件后,在其中添加以下两行,保存关闭:
    set_var EASYRSA_ALGO "ec"
    set_var EASYRSA_DIGEST "sha512"

    root@wujianjun-work:~# ./easyrsa init-pki
    root@wujianjun-work:~# ./easyrsa build-ca
    root@wujianjun-work:~# ./easyrsa gen-req server nopass
    root@wujianjun-work:~# sudo cp ~/ca/pki/private/server.key /etc/openvpn/server/
    root@wujianjun-work:~# ./easyrsa sign-req server server
    root@wujianjun-work:~# sudo cp ~/ca/pki/ca.crt /etc/openvpn/server/
    root@wujianjun-work:~# sudo cp ~/ca/pki/issued/server.crt /etc/openvpn/server/
    # 为了应对端口扫描等恶意举动,这里需要添加额外的安全措施
    root@wujianjun-work:~# openvpn --genkey --secret ta.key
    root@wujianjun-work:~# sudo cp ta.key /etc/openvpn/server/
  2. 配置服务端的文件

    1
    root@wujianjun-work:~# sudo vi /etc/openvpn/server/server.conf

    把以下内容拷贝进去

    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
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    #################################################
    # Sample OpenVPN 2.0 config file for #
    # multi-client server. #
    # #
    # This file is for the server side #
    # of a many-clients <-> one-server #
    # OpenVPN configuration. #
    # #
    # OpenVPN also supports #
    # single-machine <-> single-machine #
    # configurations (See the Examples page #
    # on the web site for more info). #
    # #
    # This config should work on Windows #
    # or Linux/BSD systems. Remember on #
    # Windows to quote pathnames and use #
    # double backslashes, e.g.: #
    # "C:\\Program Files\\OpenVPN\\config\\foo.key" #
    # #
    # Comments are preceded with '#' or ';' #
    #################################################

    # Which local IP address should OpenVPN
    # listen on? (optional)
    # 如果存在多网卡,由需要绑定具体ip地址
    ;local a.b.c.d

    # Which TCP/UDP port should OpenVPN listen on?
    # If you want to run multiple OpenVPN instances
    # on the same machine, use a different port
    # number for each one. You will need to
    # open up this port on your firewall.
    # vpn服务的监听端口
    port 1194
    ;port 1701

    # TCP or UDP server?
    ;proto tcp
    proto udp

    # "dev tun" will create a routed IP tunnel,
    # "dev tap" will create an ethernet tunnel.
    # Use "dev tap0" if you are ethernet bridging
    # and have precreated a tap0 virtual interface
    # and bridged it with your ethernet interface.
    # If you want to control access policies
    # over the VPN, you must create firewall
    # rules for the the TUN/TAP interface.
    # On non-Windows systems, you can give
    # an explicit unit number, such as tun0.
    # On Windows, use "dev-node" for this.
    # On most systems, the VPN will not function
    # unless you partially or fully disable
    # the firewall for the TUN/TAP interface.
    ;dev tap
    dev tun

    # Windows needs the TAP-Win32 adapter name
    # from the Network Connections panel if you
    # have more than one. On XP SP2 or higher,
    # you may need to selectively disable the
    # Windows firewall for the TAP adapter.
    # Non-Windows systems usually don't need this.
    ;dev-node MyTap

    # SSL/TLS root certificate (ca), certificate
    # (cert), and private key (key). Each client
    # and the server must have their own cert and
    # key file. The server and all clients will
    # use the same ca file.
    #
    # See the "easy-rsa" directory for a series
    # of scripts for generating RSA certificates
    # and private keys. Remember to use
    # a unique Common Name for the server
    # and each of the client certificates.
    #
    # Any X509 key management system can be used.
    # OpenVPN can also use a PKCS #12 formatted key file
    # (see "pkcs12" directive in man page).
    ca ca.crt
    cert server.crt
    key server.key # This file should be kept secret

    # Diffie hellman parameters.
    # Generate your own with:
    # openssl dhparam -out dh2048.pem 2048
    ;dh dh2048.pem
    dh none

    # Network topology
    # Should be subnet (addressing via IP)
    # unless Windows clients v2.0.9 and lower have to
    # be supported (then net30, i.e. a /30 per client)
    # Defaults to net30 (not recommended)
    ;topology subnet

    # Configure server mode and supply a VPN subnet
    # for OpenVPN to draw client addresses from.
    # The server will take 10.8.0.1 for itself,
    # the rest will be made available to clients.
    # Each client will be able to reach the server
    # on 10.8.0.1. Comment this line out if you are
    # ethernet bridging. See the man page for more info.
    # 给客户端分配的ip段,当前配置为10.8.0.X
    server 10.8.0.0 255.255.255.0

    # Maintain a record of client <-> virtual IP address
    # associations in this file. If OpenVPN goes down or
    # is restarted, reconnecting clients can be assigned
    # the same virtual IP address from the pool that was
    # previously assigned.
    ifconfig-pool-persist /var/log/openvpn/ipp.txt

    # Configure server mode for ethernet bridging.
    # You must first use your OS's bridging capability
    # to bridge the TAP interface with the ethernet
    # NIC interface. Then you must manually set the
    # IP/netmask on the bridge interface, here we
    # assume 10.8.0.4/255.255.255.0. Finally we
    # must set aside an IP range in this subnet
    # (start=10.8.0.50 end=10.8.0.100) to allocate
    # to connecting clients. Leave this line commented
    # out unless you are ethernet bridging.
    ;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

    # Configure server mode for ethernet bridging
    # using a DHCP-proxy, where clients talk
    # to the OpenVPN server-side DHCP server
    # to receive their IP address allocation
    # and DNS server addresses. You must first use
    # your OS's bridging capability to bridge the TAP
    # interface with the ethernet NIC interface.
    # Note: this mode only works on clients (such as
    # Windows), where the client-side TAP adapter is
    # bound to a DHCP client.
    ;server-bridge

    # Push routes to the client to allow it
    # to reach other private subnets behind
    # the server. Remember that these
    # private subnets will also need
    # to know to route the OpenVPN client
    # address pool (10.8.0.0/255.255.255.0)
    # back to the OpenVPN server.
    # 设置客户端连接上vpn后,访问不同网断所走网络。客户端软件连接上后会自动在客户机上创建网络路由
    ;push "route-gateway 10.8.0.1"
    push "route-nopull"
    # 以上配置表示客户端连接上后不额外加入任何路由
    push "route 10.84.102.0 255.255.255.0 vpn_gateway"
    # 以上配置表示客户端连接上后,访问10.84.102.X的服务器走vpn网关,下条同含义
    # vpn_gateway:表示vpn网关;net_gateway:表示走本机网络网关
    push "route 10.8.0.0 255.255.255.0 vpn_gateway"


    # To assign specific IP addresses to specific
    # clients or if a connecting client has a private
    # subnet behind it that should also have VPN access,
    # use the subdirectory "ccd" for client-specific
    # configuration files (see man page for more info).

    # EXAMPLE: Suppose the client
    # having the certificate common name "Thelonious"
    # also has a small subnet behind his connecting
    # machine, such as 192.168.40.128/255.255.255.248.
    # First, uncomment out these lines:
    ;client-config-dir ccd
    ;route 10.84.0.0 255.255.255.0
    # Then create a file ccd/Thelonious with this line:
    # iroute 192.168.40.128 255.255.255.248
    # This will allow Thelonious' private subnet to
    # access the VPN. This example will only work
    # if you are routing, not bridging, i.e. you are
    # using "dev tun" and "server" directives.

    # EXAMPLE: Suppose you want to give
    # Thelonious a fixed VPN IP address of 10.9.0.1.
    # First uncomment out these lines:
    ;client-config-dir ccd
    ;route 10.9.0.0 255.255.255.252
    # Then add this line to ccd/Thelonious:
    # ifconfig-push 10.9.0.1 10.9.0.2

    # Suppose that you want to enable different
    # firewall access policies for different groups
    # of clients. There are two methods:
    # (1) Run multiple OpenVPN daemons, one for each
    # group, and firewall the TUN/TAP interface
    # for each group/daemon appropriately.
    # (2) (Advanced) Create a script to dynamically
    # modify the firewall in response to access
    # from different clients. See man
    # page for more info on learn-address script.
    ;learn-address ./script

    # If enabled, this directive will configure
    # all clients to redirect their default
    # network gateway through the VPN, causing
    # all IP traffic such as web browsing and
    # and DNS lookups to go through the VPN
    # (The OpenVPN server machine may need to NAT
    # or bridge the TUN/TAP interface to the internet
    # in order for this to work properly).
    # 打开下行注释(去掉;号)表示强制代理所有流量
    ;push "redirect-gateway def1 bypass-dhcp"

    # Certain Windows-specific network settings
    # can be pushed to clients, such as DNS
    # or WINS server addresses. CAVEAT:
    # http://openvpn.net/faq.html#dhcpcaveats
    # The addresses below refer to the public
    # DNS servers provided by opendns.com.
    # 设置客户端连接上之后push DNS地址到客户端
    push "dhcp-option DNS 61.139.2.69"
    push "dhcp-option DNS 208.67.220.220"

    # Uncomment this directive to allow different
    # clients to be able to "see" each other.
    # By default, clients will only see the server.
    # To force clients to only see the server, you
    # will also need to appropriately firewall the
    # server's TUN/TAP interface.
    # 多台客户机连接上同一个vpn后是否网络互通,如果不互通则注释掉以下配置。
    client-to-client

    # Uncomment this directive if multiple clients
    # might connect with the same certificate/key
    # files or common names. This is recommended
    # only for testing purposes. For production use,
    # each client should have its own certificate/key
    # pair.
    #
    # IF YOU HAVE NOT GENERATED INDIVIDUAL
    # CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
    # EACH HAVING ITS OWN UNIQUE "COMMON NAME",
    # UNCOMMENT THIS LINE OUT.
    ;duplicate-cn

    # The keepalive directive causes ping-like
    # messages to be sent back and forth over
    # the link so that each side knows when
    # the other side has gone down.
    # Ping every 10 seconds, assume that remote
    # peer is down if no ping received during
    # a 120 second time period.
    keepalive 10 120

    # For extra security beyond that provided
    # by SSL/TLS, create an "HMAC firewall"
    # to help block DoS attacks and UDP port flooding.
    #
    # Generate with:
    # openvpn --genkey --secret ta.key
    #
    # The server and each client must have
    # a copy of this key.
    # The second parameter should be '0'
    # on the server and '1' on the clients.
    ;tls-auth ta.key 0 # This file is secret
    tls-crypt ta.key

    # Select a cryptographic cipher.
    # This config item must be copied to
    # the client config file as well.
    # Note that v2.4 client/server will automatically
    # negotiate AES-256-GCM in TLS mode.
    # See also the ncp-cipher option in the manpage
    ;cipher AES-256-CBC
    cipher AES-256-GCM
    auth SHA256

    # Enable compression on the VPN link and push the
    # option to the client (v2.4+ only, for earlier
    # versions see below)
    ;compress lz4-v2
    ;push "compress lz4-v2"

    # For compression compatible with older clients use comp-lzo
    # If you enable it here, you must also
    # enable it in the client config file.
    ;comp-lzo

    # The maximum number of concurrently connected
    # clients we want to allow.
    ;max-clients 100

    # It's a good idea to reduce the OpenVPN
    # daemon's privileges after initialization.
    #
    # You can uncomment this out on
    # non-Windows systems.
    user nobody
    group nogroup

    # The persist options will try to avoid
    # accessing certain resources on restart
    # that may no longer be accessible because
    # of the privilege downgrade.
    persist-key
    persist-tun

    # Output a short status file showing
    # current connections, truncated
    # and rewritten every minute.
    status /var/log/openvpn/openvpn-status.log

    # By default, log messages will go to the syslog (or
    # on Windows, if running as a service, they will go to
    # the "\Program Files\OpenVPN\log" directory).
    # Use log or log-append to override this default.
    # "log" will truncate the log file on OpenVPN startup,
    # while "log-append" will append to it. Use one
    # or the other (but not both).
    ;log /var/log/openvpn/openvpn.log
    ;log-append /var/log/openvpn/openvpn.log

    # Set the appropriate level of log
    # file verbosity.
    #
    # 0 is silent, except for fatal errors
    # 4 is reasonable for general usage
    # 5 and 6 can help to debug connection problems
    # 9 is extremely verbose
    verb 3

    # Silence repeating messages. At most 20
    # sequential messages of the same message
    # category will be output to the log.
    ;mute 20

    # Notify the client that when the server restarts so it
    # can automatically reconnect.
    explicit-exit-notify 1
  3. 开启ipv4转发

    1
    2
    root@wujianjun-work:~# echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
    root@wujianjun-work:~# sudo sysctl -p
  4. 启动服务器OpenVPN服务

    1
    2
    3
    4
    5
    root@wujianjun-work:~# sudo systemctl -f enable openvpn-server@server.service
    root@wujianjun-work:~# sudo systemctl start openvpn-server@server.service
    # 检查udp监听是否正常
    root@wujianjun-work:~# netstat -antup|grep 1194
    udp 0 0 0.0.0.0:1194 0.0.0.0:*

生成客户端ovpn配置文件

  1. 生成客户端的密钥文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    root@wujianjun-work:~# mkdir -p ~/client_conf/keys/
    root@wujianjun-work:~# chmod -R 700 ~/client_conf/
    root@wujianjun-work:~# cd ~/ca
    root@wujianjun-work:~# ./easyrsa gen-req client1 nopass
    root@wujianjun-work:~# cp ~/ca/pki/private/client1.key ~/client_conf/keys/
    root@wujianjun-work:~# ./easyrsa sign-req client client1
    root@wujianjun-work:~# cp client1.crt ~/client_conf/keys/
    root@wujianjun-work:~# cp ~/ca/ta.key ~/client_conf/keys/
    root@wujianjun-work:~# sudo cp /etc/openvpn/server/ca.crt ~/client_conf/keys/
  2. 配置并生成客户端的认证文件

    1
    2
    root@wujianjun-work:~# mkdir -p ~/client_conf/files/
    root@wujianjun-work:~# vi ~/client_conf/base.conf

    把以下内容拷贝进去

    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
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    ##############################################
    # Sample client-side OpenVPN 2.0 config file #
    # for connecting to multi-client server. #
    # #
    # This configuration can be used by multiple #
    # clients, however each client should have #
    # its own cert and key files. #
    # #
    # On Windows, you might want to rename this #
    # file so it has a .ovpn extension #
    ##############################################

    # Specify that we are a client and that we
    # will be pulling certain config file directives
    # from the server.
    client

    # Use the same setting as you are using on
    # the server.
    # On most systems, the VPN will not function
    # unless you partially or fully disable
    # the firewall for the TUN/TAP interface.
    ;dev tap
    dev tun

    # Windows needs the TAP-Win32 adapter name
    # from the Network Connections panel
    # if you have more than one. On XP SP2,
    # you may need to disable the firewall
    # for the TAP adapter.
    ;dev-node MyTap

    # Are we connecting to a TCP or
    # UDP server? Use the same setting as
    # on the server.
    ;proto tcp
    proto udp

    # The hostname/IP and port of the server.
    # You can have multiple remote entries
    # to load balance between the servers.
    # remote server-ip 1194
    remote [Vpn服务器外网IP] 1194
    ;remote my-server-2 1194

    # Choose a random host from the remote
    # list for load-balancing. Otherwise
    # try hosts in the order specified.
    ;remote-random

    # Keep trying indefinitely to resolve the
    # host name of the OpenVPN server. Very useful
    # on machines which are not permanently connected
    # to the internet such as laptops.
    resolv-retry infinite

    # Most clients don't need to bind to
    # a specific local port number.
    nobind

    # Downgrade privileges after initialization (non-Windows only)
    user nobody
    group nogroup

    # Try to preserve some state across restarts.
    persist-key
    persist-tun

    # If you are connecting through an
    # HTTP proxy to reach the actual OpenVPN
    # server, put the proxy server/IP and
    # port number here. See the man page
    # if your proxy server requires
    # authentication.
    ;http-proxy-retry # retry on connection failures
    ;http-proxy [proxy server] [proxy port #]

    # Wireless networks often produce a lot
    # of duplicate packets. Set this flag
    # to silence duplicate packet warnings.
    ;mute-replay-warnings

    # SSL/TLS parms.
    # See the server config file for more
    # description. It's best to use
    # a separate .crt/.key file pair
    # for each client. A single ca
    # file can be used for all clients.
    ;ca ca.crt
    ;cert client.crt
    ;key client.key

    # Verify server certificate by checking that the
    # certicate has the correct key usage set.
    # This is an important precaution to protect against
    # a potential attack discussed here:
    # http://openvpn.net/howto.html#mitm
    #
    # To use this feature, you will need to generate
    # your server certificates with the keyUsage set to
    # digitalSignature, keyEncipherment
    # and the extendedKeyUsage to
    # serverAuth
    # EasyRSA can do this for you.
    remote-cert-tls server

    # If a tls-auth key is used on the server
    # then every client must also have the key.
    ;tls-auth ta.key 1

    # Select a cryptographic cipher.
    # If the cipher option is used on the server
    # then you must also specify it here.
    # Note that v2.4 client/server will automatically
    # negotiate AES-256-GCM in TLS mode.
    # See also the ncp-cipher option in the manpage
    ;cipher AES-256-CBC
    cipher AES-256-GCM
    auth SHA256

    # Enable compression on the VPN link.
    # Don't enable this unless it is also
    # enabled in the server config file.
    #comp-lzo

    # Set log file verbosity.
    verb 3

    # Silence repeating messages
    ;mute 20
    key-direction 1
  3. 创建一个脚本文件用来生成客户端配置文件并对其提权

    1
    root@wujianjun-work:~# vi ~/client_conf/make_config.sh

    把以下内容拷贝进去

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    #!/bin/bash

    # First argument: Client identifier

    KEY_DIR=~/client_conf/keys
    OUTPUT_DIR=~/client_conf/files
    BASE_CONFIG=~/client_conf/base.conf

    cat ${BASE_CONFIG} \
    <(echo -e '<ca>') \
    ${KEY_DIR}/ca.crt \
    <(echo -e '</ca>\n<cert>') \
    ${KEY_DIR}/${1}.crt \
    <(echo -e '</cert>\n<key>') \
    ${KEY_DIR}/${1}.key \
    <(echo -e '</key>\n<tls-crypt>') \
    ${KEY_DIR}/ta.key \
    <(echo -e '</tls-crypt>') \
    > ${OUTPUT_DIR}/${1}.ovpn
    1
    2
    3
    4
    5
    root@wujianjun-work:~# chmod 700 ~/client_conf/make_config.sh
    root@wujianjun-work:~# cd ~/client_conf
    root@wujianjun-work:~# ./make_config.sh client1
    root@wujianjun-work:~# ls -l ~/client_conf/files
    -rw-r--r-- 1 root root 11859 Aug 3 19:29 client1.ovpn

至此,我们获得了客户端的配置文件client1.ovpn


观点仅代表自己,期待你的留言。

Ubuntu Server安装后续配置

一、开启远程root

说明

ubuntu server默认不会开启root账号

配置

1
2
3
4
5
wujianjun@wujianjun-work:~$ sudo passwd root
wujianjun@wujianjun-work:~$ su - root
wujianjun@wujianjun-work:~# vi /etc/ssh/sshd_config
在文件中添加配置:PermitRootLogin yes
wujianjun@wujianjun-work:~# /etc/init.d/ssh restart

二、固定IP配置

说明

Ubuntu 从 17.01 开始之后的版本,都已放弃在/etc/network/interfaces 里固定IP的配置,而是改成 netplan 方式,配置文件在:/etc/netplan/目录下

配置

  1. 切换到root账号,先通过ifconfig查看到网卡名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
wujianjun@wujianjun-work:~# ifconfig
enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.84.102.130 netmask 255.255.255.0 broadcast 10.84.102.255
inet6 fe80::fe34:97ff:fe67:1359 prefixlen 64 scopeid 0x20<link>
ether fc:34:97:67:13:59 txqueuelen 1000 (Ethernet)
RX packets 18835846 bytes 14116403620 (14.1 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 19693736 bytes 9492990687 (9.4 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 130834632 bytes 43706613473 (43.7 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 130834632 bytes 43706613473 (43.7 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
  1. 配置网卡enp2s0网卡固定IP
1
2
3
4
5
6
7
8
9
10
wujianjun@wujianjun-work:~# vi /etc/netplan/00-installer-config.yaml
network:
ethernets:
enp2s0:
dhcp4: no
addresses: [10.84.102.130/24]
gateway4: 10.84.102.1
nameservers:
addresses: [10.84.102.1, 61.139.2.69]
version: 2
  1. 配置生效
1
wujianjun@wujianjun-work:~# sudo netplan apply

三、免重装增加swap空间

说明

有时由于硬件自身内存不足,我们可能会使用到linux的swap来顶,swap大小按经验一般需要设置成硬件内存的2倍。

配置

  1. 切换到root

  2. 创建swap文件

1
2
3
4
5
6
wujianjun@wujianjun-work:~# mkdir /swap
wujianjun@wujianjun-work:~# cd /swap
wujianjun@wujianjun-work:~# sudo dd if=/dev/zero of=swapfile bs=32M count=1k
建立swapfile,大小为bs*count = 32M * 1k = 32G
wujianjun@wujianjun-work:~# sudo mkswap -f swapfile
将生成的文件转换为Swap文件
  1. 立即激活swap文件
1
2
3
4
5
wujianjun@wujianjun-work:~# sudo swapon swapfile
wujianjun@wujianjun-work:~# free -m
total used free shared buff/cache available
Mem: 15842 12194 208 149 3439 3158
Swap: 34815 2889 31926

如果需要禁用swap文件则使用sudo swapoff swapfile

  1. 永久激活swap文件
1
2
3
wujianjun@wujianjun-work:~# sudo vi /etc/fstab
增加配置
/swap/swapfile /swap swap defaults 0 0

四、调整swap启用时间

说明

ubuntu 和 centos 一般默认都是 60 ,就是当内存使用=(100%-60%)*内存总量时则会使用swap缓存,如需调整尽量使用物理内存,由需要调整swappiness参数值

配置

1
2
3
4
5
6
wujianjun@wujianjun-work:~# cat /proc/sys/vm/swappiness
默认值 60
wujianjun@wujianjun-work:~# sysctl vm.swappiness=10 # 临时调整
wujianjun@wujianjun-work:~# echo "vm.swappiness=10" >> /etc/sysctl.conf #永久调整
wujianjun@wujianjun-work:~# sysctl -p
vm.swappiness = 10

观点仅代表自己,期待你的留言。