Shadowsocks on Linux – Part 2: Setting Up Shadowsocks as a systemd Service

Using systemd to run Shadowsocks as a service on Linux allows it to start automatically on boot and provides more stability by ensuring automatic restarts if it encounters any issues. This guide walks you through creating a custom systemd service for Shadowsocks (sslocal) with a manual configuration option for a global proxy setting.


Create a systemd Service for Shadowsocks

1. Create the Service File Start by creating a service file for Shadowsocks in /etc/systemd/system/:

sudo vi /etc/systemd/system/shadowsocks.service

2. Configure the Service Add the following configuration, adjusting the paths as needed:

[Unit]
Description=Shadowsocks Proxy Service
After=network.target

[Service]
# Activate the virtual environment and start sslocal with the Shadowsocks config
ExecStart=/bin/bash -c 'source /path/to/shadowsocks_env/bin/activate && /path/to/shadowsocks_env/bin/sslocal -c /path/to/shadowsocks_env/shadowsocks.json'
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target
  • ExecStart: Activates the virtual environment and runs sslocal with the specified configuration file.
  • ExecReload: Allows the service to reload without restarting the entire system.
  • Restart: Ensures the service restarts automatically upon failure. Make sure to replace /path/to/shadowsocks_env/ with the actual path to your Shadowsocks environment and configuration file.

3. Enable and Start the Service

  • Reload systemd to apply the new service configuration: sudo systemctl daemon-reload
  • Enable the service to start on boot: sudo systemctl enable shadowsocks
  • Start the service: sudo systemctl start shadowsocks
  • Stop the service: sudo systemctl stop shadowsocks

4. Verify Service Status Use the following command to check if Shadowsocks is running as expected:

sudo systemctl status shadowsocks

You should see an active (running) status if everything is configured correctly.


(Optional) Manually Configure a Global Proxy for Terminal Applications

To direct all terminal traffic through Shadowsocks, you can manually set the ALL_PROXY environment variable. This can be useful for routing applications like curl through your Shadowsocks proxy.

1. Set the Global Proxy for the Current Session

export ALL_PROXY=socks5://127.0.0.1:1080
  • This directs all terminal requests through the Shadowsocks SOCKS5 proxy.
  • To verify: Use a command like curl to test if the proxy is active.

2. Unset the Global Proxy: To remove the global proxy setting from your environment

unset ALL_PROXY

3. Verify if the ALL_PROXY has been set up:

echo $ALL_PROXY

Conclusion

With Shadowsocks configured as a systemd service, you gain the benefit of automatic startup on boot and continuous operation, thanks to systemd’s restart capability. The optional manual global proxy setting gives you flexibility to selectively route traffic through Shadowsocks as needed.