bolt Valebyte VPS desde $4/mes — NVMe, despliegue en 60s.

Obtener VPS arrow_forward
eco Principiante Tutorial/Cómo hacer

Installing and Configuring OpenVPN Server on VPS

calendar_month Aug 10, 2026 schedule 25 min de lectura visibility 23 vistas
Установка и настройка OpenVPN Server на VPS: развёртывание корпоративного VPN-сервера
info

¿Necesitas un servidor para esta guía? Ofrecemos servidores dedicados y VPS en más de 50 países con configuración instantánea.

¿Necesitas un VPS para esta guía?

Explore otras opciones de servidores dedicados en

Installation and Configuration of OpenVPN Server on VPS: Deploying a Corporate VPN Server

TL;DR

In this detailed guide, we will step-by-step configure a high-performance and secure OpenVPN server on your VPS running Ubuntu 24.04 LTS. You will get a fully functional corporate VPN, which will provide encrypted access to your internal network and protect the data of your remote employees.

  • Deploy an OpenVPN server on Ubuntu 24.04 LTS using Easy-RSA 3.x for PKI management.
  • Configure server and client configs, ensuring reliable encryption (AES-256-GCM) and authentication (TLS-Auth).
  • Install and configure the UFW firewall, as well as NAT rules for routing traffic through the VPN.
  • Implement basic server security measures, such as SSH keys, Fail2ban, and automatic updates.
  • Develop a backup strategy for key OpenVPN components and provide a script for automation.
  • Review typical problems and their solutions, and answer frequently asked questions about OpenVPN.

What we are configuring and why

Diagram: What we are configuring and why
Diagram: What we are configuring and why

In this guide, we will be configuring an OpenVPN server on a Virtual Private Server (VPS). OpenVPN is a reliable and flexible solution for creating Virtual Private Networks (VPNs), which is widely used to provide secure remote access to corporate resources, protect traffic from interception, and bypass geo-restrictions.

The main task we are addressing is the deployment of a corporate VPN server. This will allow your employees to securely connect to the company's internal network from anywhere in the world, as if they were in the office. All traffic between the client device and the server will be encrypted, preventing unauthorized access to confidential data.

Ultimately, the reader will get a fully functional OpenVPN server, capable of accepting connections from multiple clients, with configured encryption, authentication, and routing rules. We will cover all stages: from server preparation to creating client configurations and maintenance recommendations.

Alternatives and why Self-Hosted on VPS

There are several approaches to organizing a VPN:

  • Cloud-Managed VPN Services: Providers such as AWS VPN Client, Google Cloud VPN, or Azure VPN Gateway offer ready-made solutions. They are easy to manage, scalable, and do not require deep configuration knowledge. However, they can be more expensive, offer less flexibility in customization, and you depend on the policies and infrastructure of a third-party provider.
  • Other Self-Hosted Solutions:
    • WireGuard: A modern, fast, and easy-to-configure VPN protocol. It has a smaller codebase, which theoretically enhances security. Excellent for simple scenarios and high performance.
    • IPsec/IKEv2: Often used in corporate networks, supported by most operating systems. More complex to configure, but offers a high degree of security and performance.
    • SoftEther VPN: A multi-protocol VPN server supporting OpenVPN, L2TP/IPsec, MS-SSTP, EtherIP, and SoftEther VPN protocols.

Why Self-Hosted OpenVPN on VPS?

The choice of OpenVPN on VPS is justified for several reasons:

  • Full Control: You fully control the server, its configuration, data, and security. This is critically important for corporate data and compliance with privacy policies.
  • Cost-effectiveness: The cost of renting a VPS is usually significantly lower than monthly payments for managed cloud VPN services, especially for a small or medium number of users.
  • Flexibility and Customization: OpenVPN is extremely flexible. You can configure it to meet any specific requirements of your network, use various authentication methods (certificates, login/password, PAM), routing, and much more.
  • Proven Reliability: OpenVPN has existed for many years, has a huge community, and is considered one of the most reliable and secure VPN protocols. Its security has been repeatedly verified and confirmed.
  • Cross-Platform Compatibility: OpenVPN clients are available for almost all operating systems (Windows, macOS, Linux, Android, iOS), which simplifies connecting employees with any devices.

Configuring OpenVPN on a VPS is an ideal balance between control, security, flexibility, and cost for most small and medium-sized companies, as well as for individual users who need reliable protection.

What VPS config is needed for this task

Diagram: What VPS config is needed for this task
Diagram: What VPS config is needed for this task

Choosing the right VPS config is crucial for ensuring stable and performant operation of the OpenVPN server. Requirements depend on the estimated number of concurrent users, the volume of traffic transferred, and the intensity of its use.

Minimum Requirements for OpenVPN Server (up to 10-20 users)

  • CPU: 1 core (x86-64). OpenVPN is not heavily CPU-dependent, but encryption requires some power. Modern processors with AES-NI instructions significantly speed up the process.
  • RAM: 512 MB - 1 GB. This will be sufficient for the operating system itself and OpenVPN. With a large number of clients or intensive logging, more may be required.
  • Disk: 10-20 GB SSD. SSD significantly speeds up OS operation and log reading/writing. The main space will be occupied by the OS; OpenVPN itself and its configurations take up very little space.
  • Network: 100 Mbps with unlimited traffic (or a very large limit). Network bandwidth is the primary factor for VPN. Make sure your tariff plan does not have strict traffic or speed limits.

Recommended VPS Plan for Corporate Use (20-50+ users)

For more serious corporate use, where stability and high bandwidth are required for a larger number of users, the following config is recommended:

  • CPU: 2 vCPU (virtual cores).
  • RAM: 2 GB - 4 GB. This will provide headroom for the operating system, OpenVPN, and potential additional services (monitoring, extended logs).
  • Disk: 40 GB - 80 GB SSD. Sufficient for OS, logs, backups, and other utilities.
  • Network: 1 Gbps with unlimited traffic. This is critically important for ensuring high data transfer speeds for all connected clients.

For such characteristics, you can consider a VPS with the specified characteristics.

When a Dedicated Server is needed, not a VPS

A dedicated server becomes necessary when:

  • Very large number of users: More than 100-200 concurrently connected clients actively using the VPN.
  • Extremely high bandwidth: If the VPN is used for transferring very large volumes of data (e.g., video streaming, large file transfers) on a continuous basis, and 1 Gbps on a VPS becomes insufficient.
  • Specific security or hardware requirements: If you need physical control over the equipment, special hardware security modules (HSM), or very high disk subsystem performance.
  • Guaranteed performance: On a dedicated server, you do not share resources with other users, which provides predictable and stable performance.

For these scenarios, you can consider a suitable dedicated server.

VPS Location: What it affects

Choosing the VPS location is of significant importance:

  • Latency: The closer the server is to most of your users, the lower the latency (ping) will be, which directly affects response speed and overall work comfort. For a corporate VPN, choose a location as close as possible to the primary location of your employees.
  • Legislation: Data storage and information privacy laws vary in different countries. Ensure that the chosen location complies with your company's requirements and applicable regulations (e.g., GDPR).
  • Availability and Bandwidth: Some regions have better network infrastructure and higher bandwidth to other parts of the world.

Always choose a location that optimizes performance for your users and complies with your legal requirements.

Server Preparation

Diagram: Server Preparation
Diagram: Server Preparation

Before proceeding with OpenVPN installation, it is necessary to perform initial setup of your VPS to ensure security and stability. We will use Ubuntu 24.04 LTS (Noble Numbat) as the base, as it is a current and supported version for 2026.

1. Connecting to the Server

Connect to your VPS via SSH using the credentials provided by your provider (usually root login and password or an SSH key).


ssh root@ВАШ_IP_АДРЕС_VPS

2. System Update

First, update the package list and installed packages to their latest versions. This will ensure you have all current security and stability fixes.


sudo apt update && sudo apt upgrade -y

If the kernel or other critical components have been updated, a reboot may be required:


sudo reboot

After rebooting, reconnect to the server.

3. Creating a New User with Sudo Privileges

Working as the root user is insecure. Let's create a new user and grant them sudo privileges.


# Replace 'your_username' with your desired username
sudo adduser ваш_пользователь

Follow the prompts to set a password and fill in (or skip) additional information.

Add the new user to the sudo group so they can execute commands with administrative privileges:


sudo usermod -aG sudo ваш_пользователь

Now, exit the root session and log in as the new user:


exit
ssh ваш_пользователь@ВАШ_IP_АДРЕС_VPS

4. Configuring SSH Keys (Recommended)

For enhanced security, it is recommended to use SSH keys instead of passwords. If you don't already have an SSH key pair, generate them on your local machine:


# On your local machine
ssh-keygen -t rsa -b 4096 -C "ваш[email protected]"

Copy the public key to the server:


# On your local machine
ssh-copy-id ваш_пользователь@ВАШ_IP_АДРЕС_VPS

If ssh-copy-id is not available, copy the key manually:


# On your local machine
cat ~/.ssh/id_rsa.pub

Then, on the server (as your new user):


mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys

Paste the copied public key into the authorized_keys file, save, and close. Set the correct permissions:


chmod 600 ~/.ssh/authorized_keys

Now you can disable password authentication for SSH (optional, but recommended). Edit the SSH daemon configuration file:


sudo nano /etc/ssh/sshd_config

Find and modify the following lines (or add them if they are missing):


# Disable root login (if you created a user)
PermitRootLogin no
# Disable password authentication (after verifying key login!)
PasswordAuthentication no
# Allow key authentication
PubkeyAuthentication yes

Restart the SSH service:


sudo systemctl restart sshd

IMPORTANT: Before exiting the current session, open a new terminal session and ensure you can log in with your SSH key as the new user. If something goes wrong, you will still have the old session open to fix errors.

5. Firewall Configuration (UFW)

UFW (Uncomplicated Firewall) is a convenient wrapper for iptables. We will configure it for basic server protection.


sudo apt install ufw -y

Allow SSH connections (default port 22). If you are using a different port for SSH, specify it:


sudo ufw allow OpenSSH
# Or, if you changed the SSH port to, for example, 2222:
# sudo ufw allow 2222/tcp

Allow connections for OpenVPN. By default, OpenVPN uses UDP port 1194. We will use this port.


sudo ufw allow 1194/udp

Enable UFW:


sudo ufw enable

Confirm the action by typing y. Check the firewall status:


sudo ufw status verbose

6. Installing Fail2ban

Fail2ban scans log files for suspicious activity (e.g., failed SSH login attempts) and blocks attacker IP addresses using firewall rules.


sudo apt install fail2ban -y

Create a copy of the default configuration file to avoid losing changes during updates:


sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit jail.local to configure the parameters. For most cases, the default settings for SSH ([sshd] section) are sufficient, but you can change bantime (ban time) and findtime (period for detecting attempts) as desired.


sudo nano /etc/fail2ban/jail.local

Ensure that the [sshd] section has enabled = true:


[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s

Restart Fail2ban:


sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

Check the status:


sudo systemctl status fail2ban
sudo fail2ban-client status sshd

Your server is now securely prepared for OpenVPN installation.

Software Installation — Step-by-Step

Diagram: Software Installation — Step-by-Step
Diagram: Software Installation — Step-by-Step

In this section, we will install OpenVPN and Easy-RSA, and then configure the Public Key Infrastructure (PKI) for secure authentication. We will use Easy-RSA version 3.x, which is current for 2026 and provides reliable certificate management.

1. Installing OpenVPN and Easy-RSA

We will install the necessary packages from the official Ubuntu 24.04 LTS repositories.


# Update package list
sudo apt update
# Install OpenVPN and Easy-RSA
sudo apt install openvpn easy-rsa -y

As of 2026, OpenVPN version 2.6.x or newer, and Easy-RSA 3.x will most likely be available.

2. PKI Preparation with Easy-RSA

Easy-RSA is a set of scripts for creating and managing a Public Key Infrastructure (PKI), which is essential for OpenVPN. All certificates and keys will be stored in a separate directory.


# Create directory for PKI
sudo make-cadir /etc/openvpn/easy-rsa
# Navigate to Easy-RSA directory
cd /etc/openvpn/easy-rsa

3. Initializing PKI

We will initialize the PKI. This will create the necessary subdirectories and files.


# Initialize PKI
sudo ./easyrsa init-pki

4. Creating a Certificate Authority (CA)

A Certificate Authority (CA) is the root certificate that will sign all other certificates (server and client). It forms the basis of trust in your VPN network.


# Create CA. When prompted for Common Name (CN), enter something meaningful, e.g., "Corporate OpenVPN CA"
sudo ./easyrsa build-ca nopass

nopass means that no password will be set for the root key. For maximum security, you can set a password, but then you will have to enter it every time you perform an action with the CA.

5. Generating Server Certificate and Key

Now we will create a certificate request for our OpenVPN server, sign it with the CA, and generate the key.


# Generate server certificate request. When prompted for Common Name (CN), enter "server"
sudo ./easyrsa gen-req server nopass
# Sign the server certificate request using the CA
sudo ./easyrsa sign-req server server

When prompted for confirmation, type yes.

6. Generating Diffie-Hellman (DH) Parameters

Diffie-Hellman parameters are used for secure key exchange between the server and clients. This process can take some time (up to several minutes depending on your VPS's power).


# Generate Diffie-Hellman parameters
sudo ./easyrsa gen-dh

7. Creating an HMAC Key (tls-auth)

The HMAC key (or tls-auth) adds an extra layer of security, protecting the TLS handshake from Denial-of-Service (DoS) attacks and port scanning. It is used for pre-authenticating packets.


# Generate HMAC key
openvpn --genkey --secret /etc/openvpn/easy-rsa/pki/ta.key

8. Copying PKI Files to the OpenVPN Server

We will move all generated files necessary for the OpenVPN server to its configuration directory.


# Create directory for OpenVPN server configs
sudo mkdir -p /etc/openvpn/server
# Copy CA certificate
sudo cp pki/ca.crt /etc/openvpn/server/
# Copy server certificate and key
sudo cp pki/issued/server.crt /etc/openvpn/server/
sudo cp pki/private/server.key /etc/openvpn/server/
# Copy Diffie-Hellman parameters
sudo cp pki/dh.pem /etc/openvpn/server/dh.pem
# Copy HMAC key
sudo cp pki/ta.key /etc/openvpn/server/ta.key

9. Generating Client Certificate and Key (Example for One Client)

For each client that will connect to the VPN, a unique certificate/key pair must be generated. Here we will show an example for one client named client1.


# Generate client certificate request. When prompted for Common Name (CN), enter "client1"
sudo ./easyrsa gen-req client1 nopass
# Sign the client certificate request using the CA
sudo ./easyrsa sign-req client client1

When prompted for confirmation, type yes. These files (client1.crt, client1.key, ca.crt, ta.key) will be needed by the client for connection. We will assemble them into a single .ovpn file later.

At this stage, the main OpenVPN components are installed, and the PKI is configured. Now let's move on to the server configuration itself.

Configuration

Diagram: Configuration
Diagram: Configuration

After installing OpenVPN and generating all necessary keys and certificates, the next step is to configure the server configuration file, routing rules, and firewall.

1. Creating the OpenVPN Server Configuration File

Let's create the server.conf file in the /etc/openvpn/server/ directory. This file will define how your OpenVPN server operates.


sudo nano /etc/openvpn/server/server.conf

Insert the following content. This is a well-balanced configuration for most corporate needs. Comments explain each option.


# Specifies that this is a server
port 1194
proto udp
dev tun

# CA, server certificate, server key files
ca ca.crt
cert server.crt
key server.key
# Diffie-Hellman parameters
dh dh.pem
# HMAC key for protection against DoS attacks and port scanning
tls-auth ta.key 0

# IP address range from which OpenVPN will assign addresses to clients
# Important: this range must not overlap with your local network
server 10.8.0.0 255.255.255.0

# Redirect all client traffic through the VPN.
# If you want clients to only have access to your corporate network,
# but not use VPN for all internet traffic, comment out this line.
push "redirect-gateway def1 bypass-dhcp"

# DNS servers to be used by clients.
# Public DNS from Cloudflare and Google are specified here.
# You can specify internal DNS of your corporate network.
push "dhcp-option DNS 1.1.1.1"
push "dhcp-option DNS 8.8.8.8"

# Allows clients to see each other (necessary if you want
# clients to interact with each other via VPN)
client-to-client

# Preserves key and tun/tap device state across restarts,
# which helps avoid connection drops during temporary issues.
keepalive 10 120
persist-key
persist-tun

# Encryption and authentication type. AES-256-GCM is modern and secure.
# SHA256 - for hashing.
cipher AES-256-GCM
auth SHA256

# Data compression (lz4-v2 - modern and efficient).
# If you have performance issues, try commenting out this line.
compress lz4-v2

# Drops root privileges after startup
user nobody
group nogroup

# Certificate Revocation List.
# Necessary for revoking compromised or outdated client certificates.
# We will create this file later.
crl-verify crl.pem

# Log verbosity (0-9). 3 is a good balance for debugging.
verb 3
# Status and log file
status /var/log/openvpn-status.log
log /var/log/openvpn.log

Save the file (Ctrl+O, Enter, Ctrl+X).

2. Enabling IP Forwarding

For OpenVPN to be able to route traffic between clients and the internet (or your internal network), IP forwarding must be enabled on the server.


sudo nano /etc/sysctl.conf

Find the line #net.ipv4.ip_forward=1, uncomment it (remove #) or add it if it's missing:


net.ipv4.ip_forward=1

Apply changes without rebooting:


sudo sysctl -p

3. Configuring NAT (Masquerading) Rules for UFW

For OpenVPN clients to be able to access the internet through your VPS, you need to configure NAT (Network Address Translation) or "masquerading". UFW does not support NAT directly by default, so we will edit its configuration files.

First, find out the name of your primary network interface. This is usually eth0 or ens3.


ip a

In the output, find the interface that has your public IP address (e.g., eth0).


# Replace 'eth0' with the name of your primary network interface
sudo nano /etc/ufw/before.rules

Add the following lines to the very beginning of the file, before the filter line:


# START OPENVPN RULES
# Allow traffic from OpenVPN client to eth0 (replace eth0 with your main network interface)
nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
COMMIT
# END OPENVPN RULES

Don't forget to replace eth0 with the name of your primary network interface if it's different. 10.8.0.0/24 is the OpenVPN subnet we specified in server.conf.

Now, edit the /etc/default/ufw file to allow forwarding by default.


sudo nano /etc/default/ufw

Find the line DEFAULT_FORWARD_POLICY="DROP" and change it to:


DEFAULT_FORWARD_POLICY="ACCEPT"

Reload UFW to apply all changes:


sudo ufw disable
sudo ufw enable

Check the UFW status. Allowed ports should now be displayed in the rules.


sudo ufw status verbose

4. Starting and Verifying the OpenVPN Server

Now that everything is configured, you can start the OpenVPN server.


# Start the OpenVPN service, specifying the name of our config (server.conf)
sudo systemctl start openvpn-server@server
# Enable OpenVPN autostart on system boot
sudo systemctl enable openvpn-server@server

Check the service status to ensure it's running without errors:


sudo systemctl status openvpn-server@server

The output should contain Active: active (running). If there are errors, check the logs:


sudo journalctl -u openvpn-server@server

Also, ensure that OpenVPN is listening on port 1194 UDP:


sudo ss -tulnp | grep 1194

You should see a line indicating that OpenVPN is listening on port 1194.

5. Creating a Client Configuration File

To connect clients, you will need an .ovpn file containing all necessary information: certificates, keys, and server settings. Let's create a script to generate such files.


sudo nano /etc/openvpn/easy-rsa/generate_client_config.sh

Insert the following script:


#!/bin/bash

# Script for generating client .ovpn files
# Run from the /etc/openvpn/easy-rsa/ directory

if [ -z "$1" ]; then
    echo "Usage: $0 "
    exit 1
fi

CLIENT_NAME=$1
OVPN_DIR="/etc/openvpn/client_configs"
EASY_RSA_DIR="/etc/openvpn/easy-rsa"
SERVER_PUBLIC_IP=$(curl -s ifconfig.me) # Получаем публичный IP сервера

mkdir -p "$OVPN_DIR"

# Генерируем клиентский запрос и ключ
cd "$EASY_RSA_DIR" || exit
./easyrsa gen-req "$CLIENT_NAME" nopass
./easyrsa sign-req client "$CLIENT_NAME"

# Собираем все необходимые файлы в один .ovpn
echo "client" > "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "dev tun" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "proto udp" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "remote ${SERVER_PUBLIC_IP} 1194" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "resolv-retry infinite" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "nobind" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "persist-key" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "persist-tun" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "remote-cert-tls server" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "cipher AES-256-GCM" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "auth SHA256" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "compress lz4-v2" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "verb 3" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "explicit-exit-notify 1" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"

echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
cat pki/ca.crt >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"

echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
cat pki/issued/"${CLIENT_NAME}".crt >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"

echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
cat pki/private/"${CLIENT_NAME}".key >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"

echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
cat pki/ta.key >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"
echo "" >> "${OVPN_DIR}/${CLIENT_NAME}.ovpn"

echo "Client file ${OVPN_DIR}/${CLIENT_NAME}.ovpn successfully created."
echo "Copy it to the client device and use it with the OpenVPN client."

Make the script executable:


sudo chmod +x /etc/openvpn/easy-rsa/generate_client_config.sh

Now you can generate client .ovpn files by running the script with the client's name:


cd /etc/openvpn/easy-rsa
sudo ./generate_client_config.sh client1

After creating the file, it needs to be copied to the client device (e.g., using scp).


# On your local computer
scp ваш_пользователь@ВАШ_IP_АДРЕС_VPS:/etc/openvpn/client_configs/client1.ovpn ~/Downloads/

Now you can use this client1.ovpn file with the OpenVPN client on your device.

6. Verifying Functionality

Connect to the VPN from the client device using the generated client1.ovpn file. After connecting:

  • Check IP address: Open a website like whatismyip.com. You should see your VPS's IP address.
  • Check routing: Try pinging a public resource (e.g., ping google.com) and internal resources if they are accessible via VPN.
  • Check DNS: Ensure that the DNS servers you specified in server.conf (e.g., 1.1.1.1) are being used.

On the server side, you can check active connections:


sudo cat /var/log/openvpn-status.log

This will show a list of connected clients.

Backups and Maintenance

Diagram: Backups and Maintenance
Diagram: Backups and Maintenance

Regular backups and timely maintenance of the OpenVPN server are critically important for ensuring its reliability, security, and continuous operation.

What to Back Up

For the OpenVPN server, the following components are most important:

  • PKI Directory: /etc/openvpn/easy-rsa/. Contains your Certificate Authority (CA), all generated certificates and keys (server and clients), as well as the PKI database. This is the most important component, without which you will not be able to issue new certificates or revoke old ones.
  • Server Configs: /etc/openvpn/server/. Contains server.conf, copies of ca.crt, server.crt, server.key, dh.pem, ta.key.
  • CRL (Certificate Revocation List): /etc/openvpn/server/crl.pem (if you created it). A list of revoked certificates.
  • Client Configs: /etc/openvpn/client_configs/. Contains generated client .ovpn files.

For a full recovery, it is sufficient to have a backup of the /etc/openvpn/ directory.

Simple Auto-Backup Script

Let's create a simple script that will archive important directories and save them to a secure location.


sudo nano /usr/local/bin/backup_openvpn.sh

Insert the following content:


#!/bin/bash

# Directories to backup
BACKUP_DIRS="/etc/openvpn"
# Directory for storing backups on the server (can be changed)
LOCAL_BACKUP_DIR="/var/backups/openvpn"
# Archive name
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
ARCHIVE_NAME="openvpn_backup_${TIMESTAMP}.tar.gz"

echo "Starting OpenVPN backup to ${LOCAL_BACKUP_DIR}/${ARCHIVE_NAME}"

# Create backup directory if it doesn't exist
mkdir -p "$LOCAL_BACKUP_DIR"

# Create archive
sudo tar -czf "${LOCAL_BACKUP_DIR}/${ARCHIVE_NAME}" "$BACKUP_DIRS"

# Delete old backups (keep only the last 7 days)
find "$LOCAL_BACKUP_DIR" -type f -name "openvpn_backup_*.tar.gz" -mtime +7 -delete

echo "Backup completed. File: ${LOCAL_BACKUP_DIR}/${ARCHIVE_NAME}"

# Optional: copy backup to remote S3 or another server
# Example for rclone (requires rclone installation and configuration)
# rclone copy "${LOCAL_BACKUP_DIR}/${ARCHIVE_NAME}" "my-s3-remote:openvpn-backups/"

# Example for SCP to another VPS (requires passwordless SSH key setup)
# scp "${LOCAL_BACKUP_DIR}/${ARCHIVE_NAME}" user@another_vps:/path/to/remote/backups/

Make the script executable:


sudo chmod +x /usr/local/bin/backup_openvpn.sh

Now, let's configure cron to automatically execute the script. For example, daily at 3:00 AM.


sudo crontab -e

Add the following line to the end of the file:


0 3 * * * /usr/local/bin/backup_openvpn.sh > /dev/null 2>&1

Save and close. Now backups will be created automatically.

Where to Store Backups

Storing backups on the same server as the original data is insecure. In case of a VPS failure, you will lose everything. It is recommended to use external storage:

  • S3-compatible cloud storage: AWS S3, Backblaze B2, DigitalOcean Spaces, MinIO. These are reliable and scalable solutions. Use utilities like rclone for synchronization.
  • Separate VPS: You can rent a small, inexpensive VPS in a different location specifically for storing backups. Synchronization can be configured via rsync over SSH.
  • Local storage (for small companies): If you have reliable local storage (NAS, server) with a good internet connection, you can configure scp or rsync to copy backups there.

Important: Always encrypt backups before sending them to external storage if it does not offer server-side encryption (e.g., using gpg or restic/borg).

Updates: Rolling vs. Maintenance Window

Keeping the system and OpenVPN up to date is critical for security.

  • Rolling Updates:
    • OS: For Ubuntu LTS, it is recommended to use automatic security updates.
      
      sudo apt install unattended-upgrades -y
      sudo dpkg-reconfigure --priority=low unattended-upgrades
                          
      Select "Yes" for automatic installation of updates.
    • OpenVPN: Typically, OpenVPN is updated along with the system via apt upgrade. However, if you are using third-party repositories or compiling from source, you need to monitor updates manually.
  • Maintenance Window:
    • For major OS updates, OpenVPN version changes, or other critical components, it is recommended to plan a maintenance window. This allows you to test changes on a test server, perform a backup, execute the update, and ensure functionality before users are affected.
    • Be sure to inform users about scheduled maintenance windows.

CRL Management (Certificate Revocation List):

If a client certificate has been compromised or a user should no longer have access, their certificate must be revoked. CRL is used for this purpose. After revoking a certificate, the CRL needs to be updated and copied to the OpenVPN server.


# Navigate to Easy-RSA directory
cd /etc/openvpn/easy-rsa
# Revoke client certificate (e.g., client1)
sudo ./easyrsa revoke client1
# Generate new CRL
sudo ./easyrsa gen-crl
# Copy CRL to OpenVPN server
sudo cp pki/crl.pem /etc/openvpn/server/
# Restart OpenVPN to load the updated CRL
sudo systemctl restart openvpn-server@server

Regularly check the relevance of the CRL and update it if necessary.

Troubleshooting + FAQ

In this section, we will cover typical issues you might encounter when setting up and operating an OpenVPN server, and answer frequently asked questions.

Client cannot connect to the VPN server. What to check?

Problem: The OpenVPN client attempts to connect, but the connection is not established or constantly interrupted.

What to check:

  1. Server Availability: Make sure your VPS is accessible from the internet. Try ping YOUR_VPS_IP_ADDRESS from your local machine.
  2. UFW Firewall: Check if the OpenVPN port (default UDP 1194) is allowed in UFW on the server.
    sudo ufw status verbose
    Ensure there is a rule 1194/udp ALLOW IN Anywhere.
  3. OpenVPN Service: Check if the OpenVPN service is running on the server and if there are any errors in its logs.
    sudo systemctl status openvpn-server@server
    sudo journalctl -u openvpn-server@server -f
    Look for errors related to certificate, key, or configuration files.
  4. Client Configuration: Make sure the client's .ovpn file specifies the correct server IP address and port. Verify that all sections (<ca>, <cert>, <key>, <tls-auth>) contain correct data.
  5. Time Synchronization: A significant time difference between the client and server can cause issues with the TLS handshake. Ensure that the time on both machines is synchronized.

Slow VPN connection speed. How to diagnose?

Problem: The connection is established, but data transfer speed is very low.

What to check and how to fix:

  1. VPS Load: Check the CPU and RAM usage on your VPS. High load can slow down encryption.
    top
    or
    htop
    If the CPU is constantly overloaded, your VPS might not be powerful enough for the current number of users.
  2. VPS Network Channel: Check the bandwidth of your VPS's network channel. Use utilities like iperf3 for testing.
    sudo apt install iperf3 -y
    Run iperf3 -s on the server and iperf3 -c YOUR_VPS_IP_ADDRESS on the client.
  3. Encryption: Ensure your OpenVPN server uses modern and fast ciphers (e.g., AES-256-GCM). Outdated or "heavy" ciphers can slow down traffic.
  4. Compression: If you are using compression (compress lz4-v2), try disabling it by commenting out the line in server.conf and restarting OpenVPN. In some cases, compression can reduce performance, especially for already compressed data.
  5. Distance to Server: The greater the physical distance between the client and the server, the higher the latency and lower the potential throughput.

No internet or local network access behind the server after connecting to VPN.

Problem: The client connects to the VPN but cannot access the internet or resources on the corporate network.

What to check and how to fix:

  1. IP Forwarding: Ensure IP forwarding is enabled on the server.
    sysctl net.ipv4.ip_forward
    It should be net.ipv4.ip_forward = 1. If not, modify /etc/sysctl.conf and execute sudo sysctl -p.
  2. NAT/Masquerading Rules: Check NAT rules in /etc/ufw/before.rules. Make sure the line -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE is present and eth0 is replaced with your actual network interface. After changes, restart UFW.
  3. DHCP Options (DNS/Routes): Ensure that push "redirect-gateway def1 bypass-dhcp" (for all traffic) and push "dhcp-option DNS ..." are correctly configured in server.conf.
  4. UFW for Outgoing Traffic: Make sure DEFAULT_FORWARD_POLICY="ACCEPT" in /etc/default/ufw.
  5. Routes to Internal Network: If you need access to an internal corporate network, not just the internet, you need to add appropriate push "route X.X.X.X Y.Y.Y.Y" to server.conf and ensure the OpenVPN server has a route to that internal network.

What is the minimum VPS configuration suitable for an OpenVPN server?

For an OpenVPN server serving up to 10-20 users, a VPS with 1 vCPU, 512 MB - 1 GB of RAM, 10-20 GB SSD storage, and a network channel of 100 Mbps or more with unlimited traffic will be minimally suitable. This will be sufficient for basic tasks and low load.

What to choose — VPS or dedicated for this task?

The choice between a VPS and a dedicated server depends on the scale of your task:

  • VPS: Ideal for most corporate needs (up to 50-100 users) if you don't require maximum performance or specific hardware. It's a more economical and flexible solution, suitable for rapid deployment.
  • Dedicated Server: Necessary for a very large number of users (more than 100-200), extremely high bandwidth (several Gbit/s), strict requirements for physical hardware control, or if you need guaranteed performance without the influence of "neighbors" on the hypervisor.

How to add a new user to OpenVPN?

To add a new user, you need to generate a new certificate/key pair and assemble the client .ovpn file. You can use the generate_client_config.sh script we created earlier:


cd /etc/openvpn/easy-rsa
sudo ./generate_client_config.sh new_client_name
    

Then copy the generated file /etc/openvpn/client_configs/new_client_name.ovpn to the new user's device.

How to revoke a user's certificate?

If a user's certificate is compromised or the user should no longer have VPN access, their certificate should be revoked. This is done using Easy-RSA:


cd /etc/openvpn/easy-rsa
sudo ./easyrsa revoke client_name
sudo ./easyrsa gen-crl
sudo cp pki/crl.pem /etc/openvpn/server/
sudo systemctl restart openvpn-server@server
    

After this, the client with the revoked certificate will no longer be able to connect to the VPN.

OpenVPN is not starting or is working with errors. Where to look first?

If OpenVPN is not starting or you observe strange behavior, always start by reviewing the logs. Main sources:

  • Systemd logs: sudo journalctl -u openvpn-server@server -f (for real-time viewing).
  • OpenVPN log file: sudo tail -f /var/log/openvpn.log (path specified in server.conf).

Carefully examine the last lines for errors, warnings, or messages about configuration or certificate file issues. Often the problem lies in an incorrect file path, incorrect permissions, or a syntax error in server.conf.

Conclusions and Next Steps

Diagram: Conclusions and Next Steps
Diagram: Conclusions and Next Steps

In this guide, we successfully deployed and configured an OpenVPN server on your VPS, providing reliable and secure remote access for corporate needs. Now your team can securely connect to internal resources, and all their traffic will be protected by encryption. You have gained full control over your VPN infrastructure, which is a key advantage of a self-hosted solution.

Further steps for optimizing and expanding your VPN infrastructure may include:

  1. Monitoring and Logging: Set up more advanced monitoring systems (e.g., Prometheus + Grafana) to track server performance, network traffic, and the number of connected clients. Centralized logging (ELK Stack or Graylog) will help quickly identify and resolve security issues.
  2. Advanced Authentication: Consider integrating with LDAP/Active Directory or using two-factor authentication (2FA) to enhance VPN access security.
  3. Client Management Automation: For larger teams, scripts or web interfaces can be developed for automatic generation, revocation, and distribution of client certificates, significantly simplifying administration.
  4. Performance Optimization: Explore Linux kernel tuning and OpenVPN settings for maximum performance, especially if you have many users or high traffic.

¿Te fue útil esta guía?

Tus comentarios nos ayudan a mejorar nuestras guías.

Compartir esta publicación:

Envía esta guía a alguien a quien pueda resultarle útil.

Telegram VKVK WhatsApp Facebook LinkedIn XX

OpenVPN server installation and configuration on VPS: deploying an enterprise VPN server
support_agent
Valebyte Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.