whoami

Lucas Jenß

cat /etc/motd

The Coding Journal ツ — Notes taken on an epic coding journey. Technical solutions, debugging notes, and practical guides from the trenches of software development.

Close-up of white dominoes with black dots standing on green felt surface, shallow depth of field, focused mood

ls -la ~/languages/

total 8
drwxr-xr-x
▶ PHP
▶ Ruby
▶ Scala
▶ C#
▶ JavaScript
▶ Objective-C
▶ Shell Scripting

ls -la ~/toolchain/

total 7
drwxr-xr-x
▶ Typo3
▶ Akka
▶ Capistrano
▶ Git
▶ MAMP
▶ Adobe Illustrator
▶ NSTrackingArea (Cocoa)

uname -a

platforms
drwxr-xr-x
▶ Mac OS X
▶ Unix

Deploying a Ruby Evented Server with Capistrano and systemd

A Ruby evented server can handle many concurrent connections with a small process footprint, but production deployment still needs dependable process supervision. Capistrano can publish a new release, link shared files and run migrations; systemd can keep the long-running service alive, restart it after failure and collect its logs.

This arrangement suits applications hosted on an Australian VPS, cloud instance or private platform in Sydney, Melbourne, Brisbane or Perth. It also gives a clear separation of responsibilities: Capistrano changes application code, while systemd owns the running process. The result is easier to operate than starting a server from a shell session or relying on a detached screen process.

Why systemd Belongs Outside Capistrano

Capistrano is a deployment tool, not a permanent process manager. A deployment task can start a Ruby server, but that process may inherit an incomplete environment, disappear when the SSH session ends or remain attached to an old release directory. A failed event loop also needs supervision after the deployment command has finished.

systemd provides those missing controls. It starts the service at boot, applies resource and identity settings, restarts an unexpected exit and records standard output in the journal. This is useful when an Australian hosting provider reboots a VM during maintenance or when a service must recover without waiting for someone in a different time zone.

The Ruby process should stay in the foreground. Avoid application-level daemonising flags because systemd expects to track the process it launches. If the server forks itself, reports a misleading PID or closes its output streams, service status and restart behaviour become unreliable.

Preparing The Ruby Release

Create a dedicated deployment user and a stable application path, such as /srv/myapp. Capistrano commonly creates release directories below that path and updates a current symlink after a successful deployment. The systemd unit can point at /srv/myapp/current, allowing the service definition to remain unchanged while the application version changes.

The runtime must be available to the service user rather than only to an interactive shell. Ruby installed through rbenv or RVM often depends on shell initialisation files that systemd does not read. An explicit PATH, a full Ruby executable path or a wrapper script prevents the familiar “command not found” problem.

Keep secrets in a shared file outside each release, for example /srv/myapp/shared/.env or /etc/myapp/production.env. Capistrano can create a symlink into the release, while systemd can load the environment directly with EnvironmentFile. File ownership should allow the deployment user to update application files without giving the service unnecessary administrative privileges.

Writing The Service Unit

A practical unit at /etc/systemd/system/myapp.service can look like this:

[Unit]
Description=MyApp Ruby evented server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/srv/myapp/current
EnvironmentFile=/etc/myapp/production.env
Environment=RAILS_ENV=production
ExecStart=/usr/local/bin/bundle exec ruby bin/server --port 9292
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
KillSignal=SIGTERM
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target

Adjust ExecStart to the actual server command. For a Rack application, this could be bundle exec puma, bundle exec thin or an evented implementation based on EventMachine or Async. Use an absolute path to bundle when Ruby is managed outside the operating system package manager. Confirm the command manually as the service user before enabling it.

After saving the file, run sudo systemctl daemon-reload, then sudo systemctl enable --now myapp. Check systemctl status myapp and journalctl -u myapp -f. A reverse proxy such as Nginx can listen on ports 80 and 443 and forward traffic to port 9292, leaving the Ruby process unprivileged.

Connecting Capistrano To systemd

Capistrano should deploy the release first, update symlinks and perform any required database or asset tasks before asking systemd to restart. A custom task can be placed in lib/capistrano/tasks/systemd.rake:

namespace :systemd do
  task :restart do
    on roles(:app) do
      execute :sudo, :systemctl, :daemon_reload
      execute :sudo, :systemctl, :restart, fetch(:application)
    end
  end
end

after 'deploy:published', 'systemd:restart'

The service name and :application value must match. Configure limited sudo access for the deployment user rather than granting unrestricted root privileges. A sudoers rule can permit systemctl daemon-reload, systemctl restart myapp and systemctl status myapp for the relevant host.

A restart after every release briefly interrupts connections unless the server supports graceful shutdown and the proxy has suitable timeouts. Send SIGTERM, allow existing requests to finish and use a health check before directing traffic to a new process. For a busy service in Sydney or Melbourne, schedule risky migrations outside the local trading peak and account for AEST or AEDT when coordinating with an offshore team.

Capistrano can also use a systemd integration gem, but a small explicit task is often easier to audit. The same troubleshooting discipline used for a silent Rake task applies here: inspect the command, its exit status and the environment rather than assuming a successful SSH session means the service is healthy. This Rake failure guide is a useful reference for that style of debugging.

Managing Environment And Dependencies

Bundler must resolve dependencies from the deployed release using the intended lockfile. Run bundle check during deployment and fail before switching current if gems are missing. Native extensions can require packages such as build-essential, libxml2-dev or database client headers, so keep the build image and production VM aligned.

Environment values should be explicit. Set RAILS_ENV, RACK_ENV, application URLs, database credentials and event-loop tuning variables in a controlled location. Do not depend on a developer’s .bashrc, SSH agent or local timezone. Australia has several time zones, and a server running UTC is usually safer for logs, scheduled jobs and cross-state operations than silently using local wall-clock time.

Shared directories also need deliberate permissions. Capistrano should preserve log, tmp, uploaded assets and other state that must survive release rotation. Do not store sockets or PID files in an old release directory. If the evented server creates a Unix socket, place it under /run/myapp and let systemd create the directory with RuntimeDirectory=myapp.

Logging Health And Failure

Use journalctl -u myapp --since today for deployment verification and journalctl -fu myapp during live diagnosis. Ruby exceptions written to standard error will appear there when the service uses the default systemd streams. Set a journal retention policy appropriate to the host, and forward logs to a central platform if the application is spread across multiple instances.

A restart loop usually indicates a configuration, dependency or port-binding error rather than a systemd problem. Inspect systemctl show myapp -p ExecMainStatus -p NRestarts, run the exact command as myapp, and check whether another process owns the listening port. Add a sensible StartLimitIntervalSec and StartLimitBurst if a broken release could repeatedly consume resources.

Health checks should test more than whether a TCP port is open. Verify that the server can load its application, reach its database and respond through the reverse proxy. If the service protects Australian customer data, review journal access, backups and retention against the organisation’s privacy obligations rather than leaving operational logs readable by every local account.

Recommendations For A Safer Deployment

Keep the unit file under version control, even if it is installed in /etc/systemd/system by a separate provisioning step. Test a release on a staging VM before production, and document the exact Ruby, Bundler and operating system versions. Cloud instances from providers serving the Australian market may offer Sydney regions, but regional availability does not remove the need for backups and tested recovery.

Use a deployment checklist that makes a failed release visible. Capistrano should stop before switching the symlink when assets, migrations or dependency checks fail. After the restart, verify the unit state, recent journal entries, listening socket and an HTTP health endpoint. Infrastructure patterns used for larger platforms, such as this Azure VMware deployment guide, also reinforce the value of separating network, application and operational responsibilities.

  • Run the evented Ruby process as a dedicated non-root user.
  • Use absolute executable paths and an explicit production environment.
  • Keep secrets and persistent data outside Capistrano release directories.
  • Configure graceful SIGTERM handling before enabling automatic restarts.
  • Grant narrowly scoped sudo permissions for Capistrano systemd tasks.
  • Monitor service health, restart counts, logs and response latency.
  • Test rollback by switching to a known-good release and restarting safely.
Concern Capistrano systemd
Release files Publishes and links application versions Uses the selected current release
Process lifetime Runs deployment commands Starts, stops and restarts the server
Environment Provides deployment variables and shared links Loads runtime variables and working directory
Failure recovery Can report a failed deployment Can restart an unexpectedly exited process
Logs Shows command output during deployment Stores runtime output in the journal

Handling Framework And Platform Changes

A Ruby service rarely exists in isolation. A PHP administration tool, TYPO3 integration or sidecar worker may share the same host and deployment conventions. Keep each service in its own unit with separate users, ports, environment files and restart policies. A framework patch should not accidentally restart the evented server unless the release requires it.

When a dependency needs a compatibility workaround, record the reason beside the deployment code and test it against the supported runtime. The practice described in this guide to patching a TYPO3 extension is a useful reminder that narrowly scoped changes are easier to remove and review than broad modifications to vendor code.

Once the unit, Capistrano hook and health checks are in place, deployments become repeatable: publish, validate, switch, reload and observe. Apply that workflow to a staging host first, then promote it to production with a rollback release ready and the relevant on-call team aware of the maintenance window.


cat ~/interests.json

KeyValue
editorTerminal-first workflow
osMac OS X / Unix
vcsGit, distributed version control
deployCapistrano, cron automation
graphicsSVG, Adobe Illustrator troubleshooting
networkingIP validation, SSH, VPN

git log --oneline --reverse

2013-10-30

Solving SVG import issues in Adobe Illustrator CS6 and CC

When importing an SVG into Illustrator, the operation fails with an unknown error [CANT]. A workaround for this Adobe-side bug.

2013

Solving NDK build issues on OS X

Troubleshooting native development kit compilation problems on Mac OS X.

2013

Programmatically adding PHP generated TypoScript to the backend configuration

Integrating dynamically generated TypoScript into Typo3 backend setups using PHP.

2013

ArgumentError: Could not parse PKey: no start line

Debugging an SSH key parsing error encountered during deployment.

2011-08-04

Validating IP-Addresses in PHP

Using PHP filter functions with flags like FILTER_FLAG_IPV4 and FILTER_FLAG_IPV6, and understanding how filter_var handles reserved IP addresses.

2011-07-09

Cocoa: Using NSTrackingArea

A short tutorial on using Cocoa's NSTrackingArea to capture mouseEntered and mouseExited events.


cat ~/contact.txt

github: github.com/x3ro
stackoverflow: x3ro
coderwall: coderwall.com/x3ro
twitter: @x3rames