CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > How to > How to Connect Java Application to a Remote Database Using an SSH Tunnel (with Spring Boot Examples)

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

How to Connect Java Application to a Remote Database Using an SSH Tunnel (with Spring Boot Examples)

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 Β· 4 min read Β· 0 Comments
Share: in X

When your database is hosted on a remote server, especially inside a private network or cloud VPC, you should never expose the database port publicly. Instead, the safest and most developer-friendly method is to create an SSH Tunnel (SSH Port Forwarding).

An SSH tunnel lets your Java or Spring Boot application connect to a remote MySQL, PostgreSQL, or MariaDB database as if it were running locally, while the actual connection happens securely through SSH.

This guide explains how to connect any Java application (JDBC, plain Java apps, CLI tools, and Spring Boot apps) to a remote database via SSH tunneling using the recommended terminal-based method.

Table of Contents

  • ⭐ What Is an SSH Tunnel?
  • Use Cases
    • 1. Local Java development connecting to production-like DB
    • 2. Run backend apps against remote staging DB
    • 3. Remote cloud databases inside private subnets
    • 4. Debugging issues on remote DB
  • πŸ” Why SSH Tunnel Instead of Exposing DB Ports?
  • ⚑ Solution: Connect Java or Spring Boot Application Using SSH Tunnel (Terminal Method)
    • Step 1: Create SSH Tunnel Using Terminal
      • For MySQL
      • For PostgreSQL
      • Meaning:
    • Step 2: Connect From Any Java Application (Plain JDBC)
      • Java JDBC Example – MySQL
      • Java JDBC Example – PostgreSQL
    • Step 3: Connect From Spring Boot
      • Spring Boot – MySQL via SSH Tunnel
    • Spring Boot – PostgreSQL via SSH Tunnel
  • Common Errors and Fixes
    • ❌ Local port already used
    • ❌ Database access denied
    • ❌ Connection refused
  • Security Best Practices
  • Conclusion

⭐ What Is an SSH Tunnel?

SSH Tunnel (or SSH Port Forwarding) securely forwards a local port on your machine to a remote system over SSH.

Example:

Local App β†’ SSH Tunnel β†’ Remote Server β†’ Database

You get:

βœ” Encrypted communication
βœ” No exposure of DB ports
βœ” Works behind private networks
βœ” Simple setup
βœ” Perfect for Java developers

Use Cases

1. Local Java development connecting to production-like DB

Avoid exposing port 3306/5432 over the internet.

2. Run backend apps against remote staging DB

SSH tunnel provides secure access.

3. Remote cloud databases inside private subnets

Ideal for AWS EC2, Google Cloud VM, or on-premise servers.

4. Debugging issues on remote DB

View and interact with DB safely.

πŸ” Why SSH Tunnel Instead of Exposing DB Ports?

Without SSH TunnelWith SSH Tunnel
DB must be publicDB stays private
Exposed to attacksTraffic encrypted
Firewall complexitySimple forwarding
Risky in productionSecure & standard

SSH tunneling is the recommended DevOps practice.

⚑ Solution: Connect Java or Spring Boot Application Using SSH Tunnel (Terminal Method)

This method does NOT require extra code.
You open a secure tunnel β†’ your Java or Spring Boot app connects locally.

Step 1: Create SSH Tunnel Using Terminal

Go to the location where your pem file is present and open terminal from there.

For MySQL

ssh -i my-sshkey.pem -L 3307:my-mysql-host:3306 ubuntu@my-bastion-host-server-ip

For PostgreSQL

ssh -i my-sshkey.pem -L 5433:my-mysql-host:5432 ubuntu@my-bastion-host-server-ip

Meaning:

  • Remote DB ports: 3306 / 5432
  • Local forwarded ports: 3307 / 5433
  • Java application connects locally
  • SSH securely handles routing

Keep the SSH tunnel terminal open while running your app.

Step 2: Connect From Any Java Application (Plain JDBC)

Java JDBC Example – MySQL

import java.sql.Connection;
import java.sql.DriverManager;

public class TestConnection {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3307/mydatabase";
        String username = "dbuser";
        String password = "dbpass";

        Connection conn = DriverManager.getConnection(url, username, password);
        System.out.println("Connected successfully via SSH tunnel!");
    }
}

Java JDBC Example – PostgreSQL

String url = "jdbc:postgresql://localhost:5433/mydatabase";
Connection conn = DriverManager.getConnection(url, "dbuser", "dbpass");

No special SSH libraries required.

Step 3: Connect From Spring Boot

Spring Boot – MySQL via SSH Tunnel

spring.datasource.url=jdbc:mysql://localhost:3307/mydatabase
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot – PostgreSQL via SSH Tunnel

spring.datasource.url=jdbc:postgresql://localhost:5433/mydatabase
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver

Common Errors and Fixes

❌ Local port already used

Address already in use

Fix: use a different port:

-L 3308:localhost:3306

❌ Database access denied

Check DB user permissions and host restrictions.

❌ Connection refused

❑ DB may not be running
❑ Wrong remote hostname
❑ Firewall rules

Security Best Practices

βœ” Always use private keys (not passwords)
βœ” Never expose DB ports publicly
βœ” Allow SSH access only for trusted IPs
βœ” Rotate SSH keys regularly
βœ” Use strong DB passwords
βœ” Disable root login in DB

Conclusion

Connecting to a remote database through an SSH tunnel is the most secure and simplest way for Java and Spring Boot applications to access remote MySQL or PostgreSQL servers without exposing your database to the internet.

Whether you’re building:

  • a Java CLI tool,
  • a JDBC-based Java application, or
  • a Spring Boot backend

…this SSH tunneling method works flawlessly and securely.

Just create the SSH tunnel, point your application to the local port, and let SSH handle the secure connection behind the scenes.

Related Posts:

  • MySQL Commands for Developers
  • Route traffic from AWS Application Load Balancer to…
  • Control Statements in Java
  • How to Fix SSH Agent Forwarding on macOS: The…
  • JDBC Interview Questions: Ace Your Technical Screening
  • java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Tags:java
Was this article helpful?
← Previous ArticleHow to Convert JSON Array to Java List (With Examples)
Next Article β†’How to Fix NoClassDefFoundError: javax/xml/bind/DatatypeConverter in Java (Java 11+)

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
Β© 2026 CoderSathi. All rights reserved. Privacy Policy Β· Sitemap