Install an SSL certificate in a Node.js environment (Linux)

更新时间:
复制 MD 格式

This topic describes how to configure an SSL certificate on a Node.js server running Linux, including the steps to download and upload certificate files and verify the installation.

Prerequisites

  • You have purchased and applied for a certificate by using the SSL Certificates Service, and its Status is Issued. To purchase and apply for a certificate, see Purchase a paid certificate and Apply for a certificate.

  • Your domain name is correctly resolved to the current server, and you have completed the MIIT ICP filing (for servers in the Chinese mainland).

    How to check DNS records and ICP filing information

    Open the Network Probe Tool, select Network Diagnostic Analysis, enter your domain name, and confirm the following information:

    • In the DNS Provider Resolution Result section, the IP address in the A record is the public IP address of your server.

    • The ICP Filing Check status is ICP Filed. If the status is "The website is not ICP filed. Please contact the website server provider.", you must complete the ICP filing before you install the certificate.

  • You have administrative permissions on this server (a root account or an account with sudo permissions).

Procedure

Step 1: Download the SSL certificate and private key files

  1. Go to the SSL Certificate Management page, locate the target certificate to deploy, and confirm the following information:

    1. Certificate Status: Make sure the status is Issued. If the status is About to Expire or Expired, see SSL certificate renewal and expiration.

    2. Bound Domains: Make sure it can match all domain names that need to be protected. Otherwise, a security warning will appear when accessing unmatched domain names over HTTPS. If you need to add or modify domain names, see Append or change a domain name.

      Verify whether the certificate matches the target domain name

      The Bound Domains of a certificate can contain multiple exact domain names and wildcard domain names. The matching rules for each type are as follows:

      • Exact domain name: applies only to the specified domain name.

        • example.com applies only to example.com.

        • www.example.com applies only to www.example.com.

      • Wildcard domain name: applies only to its first-level subdomains.

        • *.example.com applies to first-level subdomains such as www.example.com and a.example.com.

        • *.example.com does not apply to the root domain example.com or multi-level subdomains such as a.b.example.com.

      Note

      To match multi-level subdomains, the Bound Domains must include the specific domain name (such as a.b.example.com) or the corresponding wildcard domain name (such as *.b.example.com).

  2. In the Actions column of the target certificate, click Download and download the certificate whose Server Type is Nginx.

  3. Decompress the downloaded certificate package. The package contains the following files:

    • Signing certificate: <certificate-bindng-domain>_sm2_sign.pem and <certificate-binding-domain>_sm2_sign.key

    • Encryption certificate: <certificate-binding-domain>_sm2_enc.pem and <certificate-binding-domain>_sm2_enc.key

      Note

      If you used tools such as OpenSSL or Keytool to generate a CSR file when applying for the certificate, the private key file is saved only on your local machine and is not included in the downloaded certificate package. If the private key is lost, the certificate cannot be used. You need to Purchase a commercial certificate again and generate the CSR and private key.

Step 2: Install the SSL certificate on Node.js

  1. Log on to the Linux server.

    Alibaba Cloud server

    The following operations use an Alibaba Cloud ECS instance as an example. For other types of servers, see their respective documentation.

    1. Log on to the ECS console. In the top navigation bar, select the region where the target ECS instance is located.

    2. In the left-side navigation pane, choose Instances & Images > Instances. On the Instances page, find the target ECS instance and click Remote Connection in the Remote connection column.

    3. In the dialog box that appears, select Workbench and click Sign in now.

    4. Select Terminal Connection as the connection method, enter the authentication information, and follow the on-screen instructions to complete the logon. You can then access the server terminal. For more information, see Connect to an ECS instance by using Workbench.

      Note

      If the Security Group Whitelist Opening Prompt panel appears, click Add Rule as prompted.

    Other cloud providers

    Use the remote connection feature provided by the cloud provider to log on to the server terminal.

    On-premises servers

    Use an SSH tool on your local machine to log on to the server terminal.

    • Windows: Run the ssh <username>@<server_ip_address> command in Command Prompt (cmd) or PowerShell. If the ssh command is not supported, you can use a third-party tool, such as PuTTY or WinSCP, to establish a connection.

    • macOS/Linux: Run the ssh <username>@<server_ip_address> command in the built-in terminal.

    Some of the following commands vary based on the operating system. Select the appropriate command for your server's OS.

    • RHEL/CentOS series: includes Alibaba Cloud Linux, Red Hat Enterprise Linux, CentOS, AlmaLinux, Rocky Linux, Anolis OS, and their derivatives.

    • Debian/Ubuntu series: includes Debian, Ubuntu, and their derivatives.

    How to identify your operating system series

    Run the cat /etc/os-release command in the server terminal and check the ID_LIKE and ID fields in the output.

    • If the value of ID_LIKE or ID contains rhel or centos, the operating system belongs to the RHEL/CentOS series.

    • If the value of ID_LIKE or ID contains debian or ubuntu, the operating system belongs to the Debian/Ubuntu series.

  2. Open port 443 in the security group and firewall.

    1. Run the following command in the server terminal to check whether port 443 is open:

      RHEL/CentOS

      command -v nc > /dev/null 2>&1 || sudo yum install -y nc
      # Replace <your_server_public_ip_address> with the public IP address of your server.
      sudo ss -tlnp | grep -q ':443 ' || sudo nc -l 443 & sleep 1; nc -w 3 -vz <your_server_public_ip_address> 443

      If the output contains Ncat: Connected to <your_server_public_ip_address>:443, port 443 is open. Otherwise, you must open port 443 in the security group and firewall.

      Debian/Ubuntu

      command -v nc > /dev/null 2>&1 || sudo apt-get install -y netcat
      # Replace <your_server_public_ip_address> with the public IP address of your server.
      sudo ss -tlnp | grep -q ':443 ' || sudo nc -l -p 443 & sleep 1; nc -w 3 -vz <your_server_public_ip_address> 443

      If the output contains Connection to <your_server_public_ip_address> port [tcp/https] succeeded! or [<your_server_public_ip_address>] 443 (https) open, port 443 is open. Otherwise, you must open port 443 in the security group and firewall.

    2. Open port 443 in the security group.

      Important

      If your server is deployed on a cloud platform, make sure that its security group allows inbound traffic on TCP port 443. Otherwise, the service is not accessible from the internet. The following operations use an Alibaba Cloud ECS instance as an example. For other cloud platforms, see their official documentation.

      Go to the ECS Instances page and click the name of the target instance to go to its details page. For more information, see Add a security group rule. Add a rule to the security group with Action set to Allow, Protocol Type set to TCP, Port Range set to HTTPS(443), and Authorization Object set to Anywhere (0.0.0.0/0).

    3. Open port 443 in the firewall.

      Run the following command to identify the current firewall service on your system:

      if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
          echo "firewalld"
      elif command -v ufw >/dev/null 2>&1 && sudo ufw status | grep -qw active; then
          echo "ufw"
      elif command -v nft >/dev/null 2>&1 && sudo nft list ruleset 2>/dev/null | grep -q 'table'; then
          echo "nftables"
      elif command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet iptables; then
          echo "iptables"
      elif command -v iptables >/dev/null 2>&1 && sudo iptables -L 2>/dev/null | grep -qE 'REJECT|DROP|ACCEPT'; then
          echo "iptables"
      else
          echo "none"
      fi

      If the output is none, no further action is required. Otherwise, based on the firewall type (firewalld, ufw, nftables, or iptables), run the corresponding command to open port 443:

      firewalld

      sudo firewall-cmd --permanent --add-port=443/tcp && sudo firewall-cmd --reload

      ufw

      sudo ufw allow 443/tcp

      nftables

      sudo nft add table inet filter 2>/dev/null
      sudo nft add chain inet filter input '{ type filter hook input priority 0; }' 2>/dev/null
      sudo nft add rule inet filter input tcp dport 443 counter accept 2>/dev/null

      iptables

      sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

      To prevent iptables rules from being lost after a system reboot, run the following command to make the rules persistent:

      RHEL/CentOS
      sudo yum install -y iptables-services
      sudo service iptables save
      Debian/Ubuntu
      sudo apt-get install -y iptables-persistent
      sudo iptables-save | sudo tee /etc/iptables/rules.v4 >/dev/null
  3. Upload the SSL certificate and private key files to the target directory on the server.

    Important

    This topic uses ssl.pem (certificate file) and ssl.key (private key file) as examples, and uploads them to the /etc/ssl/cert directory on the server. If this directory does not exist, run sudo mkdir -p /etc/ssl/cert to create it.

    Alibaba Cloud server

    The following operations use Alibaba Cloud Elastic Compute Service (ECS) as an example. For other types of servers, refer to the corresponding product documentation.

    1. On the logged-in Workbench page, choose File > Open New File Tree from the top menu bar.

    2. In the file tree on the left, right-click the target directory (/etc/ssl/cert), select Upload File, and select and upload the certificate file ssl.pem.

    3. Repeat the preceding operation. Right-click the target directory (/etc/ssl/cert) again, select Upload File, and select and upload the private key file ssl.key.

    4. After the upload is complete, the certificate file path is /etc/ssl/cert/ssl.pem, and the private key file path is /etc/ssl/cert/ssl.key.

    Other cloud provider servers

    Use the file upload feature provided by the corresponding cloud provider to upload the certificate and private key files to the target directory on the server (/etc/ssl/cert).

    Non-cloud servers (such as physical servers or IDC-hosted machines)

    Upload the certificate file and private key file from your local machine using an SSH tool. In the following examples, <username> is the username of the current server, and <server_ip> is the public IP address of the current server.

    Windows
    1. Use the built-in Command Prompt (cmd) or PowerShell to upload files using the scp command. The following example assumes the certificate file and private key file are located in the local C:\ directory.

      # Upload the local certificate file to the server. Replace the path C:\ssl.pem and /etc/ssl/cert with the actual source file and target directory.
      scp C:\ssl.pem <username>@<server_ip>:/etc/ssl/cert
      
      # Upload the local private key file to the server. Replace the path C:\ssl.key and /etc/ssl/cert with the actual source file and target directory.
      scp C:\ssl.key <username>@<server_ip>:/etc/ssl/cert
    2. If the scp command is not integrated into the system, you can use the open-source free PuTTY client and its bundled pscp.exe tool to upload files via the command line. You can also use the graphical WinSCP to upload files.

    Linux/macOS

    Use the built-in terminal to upload files using the scp command. The following example assumes the certificate file and private key file are located in the local /tmp directory.

    # Upload the local certificate file to the server. Replace the path /tmp/ssl.pem and /etc/ssl/cert with the actual source file and target directory.
    scp /tmp/ssl.pem <username>@<server_ip>:/etc/ssl/cert
    
    # Upload the local private key file to the server. Replace the path /tmp/ssl.key and /etc/ssl/cert with the actual source file and target directory.
    scp /tmp/ssl.key <username>@<server_ip>:/etc/ssl/cert
  4. Go to the working directory (such as /home) and create the Node.js project file https_server_test.js.

    # The /home directory is used only as an example. Replace it with your actual working directory.
    cd /home
    
    # Create a test project file. Replace it with your actual project file.
    sudo touch https_server_test.js
  5. Edit the https_server_test.js file.

    vim https_server_test.js

    Press i to enter edit mode, and add the following content to the https_server_test.js file.

    // The https module is required to start the HTTPS server
    // The fs module is required to read files
    const https = require('https');
    const fs = require('fs');
    
    // Read the two certificate files into the options object
    // Use the readFileSync() method to sequentially execute file reading and server startup operations
    const options = {
        key: fs.readFileSync('/etc/ssl/cert/ssl.key'),  // Replace with the actual absolute path of the uploaded private key file.
        cert: fs.readFileSync('/etc/ssl/cert/ssl.pem')  // Replace with the actual absolute path of the uploaded SSL certificate file.
    };
    
    // Create the server, start it, and set the listening port
    https.createServer(options, (req, res) => {
        res.end('hello world\n');
    }).listen(443);
    Important

    The certificate file paths must be configured correctly. Otherwise, the certificate configuration will fail and HTTPS access will not work.

  6. Press Esc to exit edit mode, type :wq, and then press Enter to save and exit the file.

  7. Run the following command to activate the SSL certificate.

    sudo node https_server_test.js

Step 3: Verify that the SSL certificate is installed successfully

  1. Access your domain name over HTTPS. Example: https://example.com. Replace example.com with your actual domain name.

  2. If a lock icon appears in the browser's address bar, the certificate is deployed successfully. If an access error occurs or the lock icon does not appear, clear your browser's cache or try again in incognito or private mode.

    image

    Starting with Chrome 117, the image icon in the address bar has been replaced by a new image icon. Click this icon to view the security lock information.

Note

If issues persist, refer to the FAQ for troubleshooting.

Next steps (Optional)

Enable domain monitoring

After the certificate is deployed, we recommend that you enable domain name monitoring. The system automatically checks the validity period of the certificate and sends reminders before the certificate expires. This helps you renew the certificate in a timely manner to prevent service interruptions. For more information, see Purchase and enable public domain name monitoring.

FAQ

Certificate not working or HTTPS inaccessible

Common causes are as follows:

How to update (replace) an installed SSL certificate in Node.js

Back up the original certificate files (.pem and .key) on the server first. Then log on to the Certificate Management Service console, download the new certificate files (.pem and .key), and upload them to the target server to overwrite the original files (ensure the paths and file names are consistent). Finally, restart the Node.js service to activate the new certificate.