Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › application security

How to Secure a Three-Tier Rails App with SSH Tunnels

By Freedom251 Team · · 11 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep the Rails database off the public internet by separating the deployment into a public edge, a private Rails application tier, and a private database tier. Permit only edge-to-app and app-to-database traffic, then give operators a separate, logged-in path through a bastion or provider SSH endpoint. For administration, use a local SSH forward bound to 127.0.0.1, require the forward to succeed before the session continues, and close it as soon as the task is complete.

This design protects exposure and routing, but an SSH tunnel is not a substitute for database authentication, authorization, secret management, or encryption on every network hop. The critical question is where each encrypted segment ends.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start with the three-tier boundary

A secure Rails deployment has three distinct network roles:

  • Edge tier: the public reverse proxy or load-balancing layer that accepts HTTP and HTTPS traffic.
  • Application tier: Rails processes on private addresses. They receive requests only from the edge tier and initiate database connections only to the database tier.
  • Database tier: PostgreSQL on a private address, reachable by the Rails application and by a tightly controlled administrative path, not by arbitrary internet clients.

The edge is the only tier that needs public exposure. Security groups, firewall rules, network policies, or the hosting provider’s private-network controls should express the allowed flows explicitly rather than relying on the fact that a service is hard to guess.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Flow Required source Destination Exposure Control
Web requests Internet clients Public edge Public HTTPS termination, application-layer filtering, and forwarding only to the Rails tier
Application requests Public edge Private Rails service Private Allow only the edge-to-app port and source range
Database traffic Rails service Private PostgreSQL service Private Allow only the app-to-database port and authenticate with a least-privilege database role
Operator administration Authorized operator through bastion or provider SSH endpoint Database or internal service port Private target, controlled entry point Separate identity, key review, narrow forwarding destination, and access logging

Do not expose PostgreSQL merely to make a GUI client convenient. A public address or a provider’s public TCP proxy adds a new internet-facing path that must be defended independently. Keep the private route for normal application traffic and create a temporary tunnel for maintenance.

What an SSH tunnel actually protects

Local port forwarding

With local forwarding, the SSH client opens a listening socket on your workstation. When a local program connects to that socket, SSH carries the bytes to the SSH server, which then opens a connection to the specified target and port.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The general form is:

ssh -L local_bind_address:local_port:remote_target:remote_port user@ssh_server

The remote target is resolved from the SSH server’s point of view. Therefore, remote_target can be a database hostname that is private to the bastion’s network. The local port is arbitrary; choose an unused high port so it does not conflict with a local PostgreSQL instance.

The PostgreSQL documentation demonstrates the pattern with ssh -L 63333:localhost:5432 [email protected], followed by psql -h localhost -p 63333 postgres. The same principle applies to a Rails database: the client connects to the local listener, while the SSH server reaches the private PostgreSQL endpoint.

The encryption boundary matters

SSH encrypts the connection between the SSH client and the SSH server. It does not automatically encrypt a second connection that the SSH server makes onward to another host. For example:

ssh -L 63333:db.foo.com:5432 [email protected]

encrypts the workstation-to-shell.foo.com segment. The connection from shell.foo.com to db.foo.com is outside that SSH tunnel. PostgreSQL’s guide calls out this boundary explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

There are three defensible ways to handle the onward leg:

  • Terminate SSH on the database host itself, when that is operationally and architecturally appropriate.
  • Use a second protected channel for the bastion-to-database leg, such as authenticated database TLS or another encrypted private network.
  • Use a provider private network whose transport is encrypted, while still enforcing database authentication and authorization.

A bastion is therefore a controlled entry point, not a magical encryption wrapper around every hop. Document the endpoint and protection used for each segment.

Prepare the deployment before opening a tunnel

Place services on private addresses

Put the Rails service and PostgreSQL service on private addresses or an isolated provider environment. Publish only the edge tier. Confirm that the Rails process can resolve the database’s private hostname and that the database firewall accepts connections from the Rails service’s network identity, not from the whole internet.

Create a narrow operator path

Use a dedicated bastion or a provider-managed SSH endpoint with only the network reachability required for the task. The bastion should not become a general-purpose jump box with access to every subnet. If an operator needs PostgreSQL administration, allow the PostgreSQL destination and port; do not automatically allow unrelated internal services.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate identities and keys

Give operators individual accounts or provider identities and individual SSH keys. Remove unused keys, review access logs, and expire or rotate short-lived access after maintenance. A shared “deploy” key makes attribution and revocation harder, even when the account name is convenient.

Decide whether the account needs a shell

If the platform permits it, use a tunnel-only account with interactive shells disabled. The account should be able to establish the required forward and nothing more. This reduces the impact of a stolen key and makes the intended workflow auditable.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Open a safe PostgreSQL tunnel

For an operator whose SSH endpoint can reach PostgreSQL on its own loopback address, use:

ssh -N -T -o ExitOnForwardFailure=yes 
  -L 127.0.0.1:63333:127.0.0.1:5432 
  [email protected]
  1. Check the local port. Make sure nothing else is listening on 127.0.0.1:63333. Select another high port if necessary.
  2. Verify the target from the bastion. The two 127.0.0.1 addresses mean “the SSH client’s local loopback” and “the SSH server’s loopback,” respectively. Use the database’s private hostname instead if PostgreSQL is on another private host.
  3. Run the command from a trusted workstation. The SSH host key must match the expected bastion identity. Do not bypass host-key verification to make a failed connection work.
  4. Keep the session open. -N requests forwarding only, with no remote command. -T disables a pseudo-terminal, which is appropriate for a tunnel-only session.
  5. Fail closed. ExitOnForwardFailure=yes makes SSH exit if it cannot establish the requested forward instead of leaving you with a session that appears connected but cannot carry traffic.
  6. Connect the database client locally. Point psql or a GUI client at 127.0.0.1 and port 63333, while supplying the normal database name, user, password, and any TLS settings through your approved secret mechanism.
  7. Close the tunnel. End the SSH session as soon as the administrative task is finished. A tunnel left running is an unnecessary active access path.
psql -h 127.0.0.1 -p 63333 -U admin_role -d app_production

Use a database role intended for the maintenance task rather than the application’s broadest role. Keep credentials in the normal secret store or password manager; do not put passwords in shell history, source control, or a command line that other local users can inspect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When the database is on another private host

If the bastion reaches PostgreSQL at db.internal.example, the forward becomes:

ssh -N -T -o ExitOnForwardFailure=yes 
  -L 127.0.0.1:63333:db.internal.example:5432 
  [email protected]

That command still encrypts the workstation-to-bastion leg only. Use PostgreSQL TLS, a second protected channel, or an encrypted private network for the bastion-to-database connection. Confirm the database certificate and hostname checks required by your PostgreSQL client instead of assuming that the private address alone provides encryption.

Configure Rails for private east-west traffic

The Rails application should connect directly to the database’s private hostname or private service name. The operator tunnel is a separate path for administration; it does not prove that the application path is correctly authorized.

  • Store the production database URL or its individual connection settings in the platform’s secret store.
  • Allow the database port only from the Rails service’s private network identity.
  • Use a dedicated application database role with only the privileges Rails requires.
  • Keep migrations and administrative credentials separate from the runtime credentials where your deployment process allows it.
  • Test DNS resolution, TCP reachability, credentials, and authorization from the Rails runtime itself.

Run application-path testing independently from operator testing. A successful local tunnel can coexist with a broken Rails configuration, a blocked private firewall rule, an expired secret, or a database role that lacks the required permissions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Provider private networking and SSH access

Some managed platforms provide a private service network in addition to an SSH endpoint. Railway’s documentation, for example, describes PostgreSQL as private by default; enabling public access creates a TCP Proxy and a public connection path. Prefer the private path and use the SSH tunnel for operator access rather than enabling public access for convenience.

Railway also documents a command pattern that opens a local tunnel and prints connection details for command-line or graphical clients:

railway connect --ssh --tunnel-only

The tunnel remains open while the client uses the printed local connection details. The platform describes forwarding as limited to the container loopback and project private network. Treat those provider limits as an additional boundary, not as a replacement for database credentials, role permissions, or operator identity controls.

Railway’s private-networking documentation describes encrypted WireGuard tunnels, internal DNS, traffic that stays within the provider’s infrastructure, and support for TCP database traffic. Those controls protect transport and routing between services. Rails still needs authenticated connections, safe secret handling, authorization checks, and least-privilege database roles.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Restrict the SSH server and forwarding destinations

Forwarding should be narrower than ordinary shell access. Apply the following controls on the bastion or provider endpoint:

  • Restrict AllowTcpForwarding to the forwarding mode required by the workflow.
  • Limit permitted forwarding destinations and ports to the database or internal service actually needed.
  • Disable interactive shells for tunnel-only accounts when supported.
  • Use separate operator identities and review authentication and forwarding logs.
  • Remove unused keys and rotate or expire temporary access after maintenance.
  • Keep the bastion’s own outbound network rules narrow; a tunnel is only as constrained as the SSH server’s ability to reach targets.

Do not give an operator unrestricted forwarding and rely on personal judgment to select a safe destination. Enforce the destination at the SSH or provider policy layer so a stolen key cannot be repurposed to reach unrelated internal services.

Bind the local listener to loopback

Always prefer an explicit loopback bind such as 127.0.0.1:63333. A command that omits the bind address may listen on a broader local interface depending on the SSH client’s defaults and configuration. Binding to loopback prevents other machines on the workstation’s network from using the tunnel accidentally.

Use a different local port from the remote service when convenient. There is no requirement for the local and remote port numbers to match: 63333 can forward to PostgreSQL’s remote 5432. Record the mapping in the maintenance runbook so a second operator does not connect a client to the wrong local service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Compare the main access designs

Design Public exposure Encryption coverage Identity and audit Operational trade-off
Direct public PostgreSQL endpoint Database exposed through a public address or proxy Depends on database TLS and client configuration Database logs plus provider or firewall logs Simple client connectivity, but the largest internet-facing attack surface
Bastion with local SSH forward SSH endpoint or bastion is exposed; database remains private SSH client-to-bastion; protect the onward leg separately Operator SSH identity, key review, forwarding policy, and logs Strong administrative separation, with a tunnel to open and close
Provider SSH tunnel over private service network Provider SSH endpoint is the controlled entry point SSH tunnel plus provider’s encrypted private-network transport Provider identity and tunnel logs, plus database authentication Less infrastructure to operate, but dependent on provider tooling and availability
Application-only private connection No operator route unless one is added temporarily Private-network transport and database protocol protections Rails service identity and database logs Best default for runtime traffic; not sufficient by itself for emergency administration

Evaluate any design against the same questions: Is the database publicly reachable? Is every hop encrypted? How are identities and keys issued, reviewed, and revoked? Which forwarding destinations are allowed? What evidence is logged? What does the application do when the bastion or tunnel is unavailable?

Troubleshoot by separating the path

“Connection refused” on the local port

  • Check that the SSH process is still running and that the local port is not already occupied.
  • Confirm ExitOnForwardFailure=yes did not terminate the session after a failed setup.
  • Verify that the client is using 127.0.0.1 and the same local port specified in -L.

The tunnel opens but PostgreSQL times out

  • Test whether the bastion can reach the target hostname and port from its own network.
  • Check private firewall rules between the bastion and database.
  • Confirm that the target hostname resolves from the bastion, not only from your workstation.
  • Review SSH forwarding restrictions and destination-port policy.

Authentication fails after the tunnel works

  • Verify the database name, user, password, and role privileges independently of SSH.
  • Check that the client is not accidentally using a stale local PostgreSQL socket or a different port.
  • Apply the database’s required TLS and certificate settings for the final connection.

Rails cannot connect while the operator can

  • Test from the Rails runtime rather than from the operator workstation.
  • Check the Rails secret value, private DNS name, database firewall source, and role permissions.
  • Remember that a working operator tunnel says nothing about the application’s authorization path.

The bastion is unavailable

Do not respond by enabling public database access as an improvised workaround. Use the documented break-glass path, restore the bastion or provider endpoint, or perform the task from an approved private-network location. Record the outage and any temporary access change, then remove that change when service is restored.

Use a repeatable maintenance runbook

  1. Open an approved maintenance ticket describing the database, task, operator, and expected duration.
  2. Confirm the operator identity, bastion host key, allowed destination, and database role.
  3. Check that the Rails application is healthy before changing data or schema.
  4. Start the loopback-bound tunnel with -N, -T, and ExitOnForwardFailure=yes.
  5. Connect with the least-privilege database account and capture the required audit information.
  6. Perform the task without copying production secrets into shell history, scripts, or source control.
  7. Close the tunnel, revoke or expire temporary access, and verify that the database is still private.
  8. Record the result and any failed connection attempts in the operational log.

Security checklist

  • Public edge only; Rails and PostgreSQL use private addresses.
  • Edge-to-app and app-to-database flows are explicitly allowed and all others are denied.
  • Operator access uses a dedicated bastion or provider SSH endpoint.
  • Individual identities and keys are reviewed, rotated, and removed when unused.
  • Tunnel-only accounts have no interactive shell where the platform supports that restriction.
  • Forwarding destinations and ports are constrained by SSH or provider policy.
  • Local forwards bind to 127.0.0.1 and use an intentionally selected high port.
  • ExitOnForwardFailure=yes is enabled for administrative tunnels.
  • PostgreSQL credentials and Rails secrets remain in an approved secret store.
  • The bastion-to-database leg has its own encryption or protected private-network guarantee.
  • Application-path testing is performed separately from operator-tunnel testing.
  • Temporary tunnels are closed and short-lived access is rotated or expired after use.

Bottom line

Secure the Rails application by making the database private, limiting runtime traffic to the two flows the application needs, and treating administration as a separate, auditable operation. A loopback-bound local SSH forward lets an operator reach a private PostgreSQL port without publishing it, while ExitOnForwardFailure=yes, narrow forwarding policy, individual keys, and prompt tunnel closure reduce accidental exposure. Always verify the encryption and authentication of the bastion-to-database leg; the SSH client-to-bastion tunnel alone does not protect that hop.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

application securitybastion hostPostgreSQLprivate networkingRuby on RailsSSH tunnels

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.