Skip to Content
문서서버데이터 베이스

데이터베이스

26.10 버전 차이

26.10은 MySQL을 8.4 LTS에서 9.7 LTS(릴리스 노트의 9.7.2)로 이동하고 Valkey를 포함합니다. 9.1.2. 아래 26.04 절차는 주요 버전 마이그레이션 지침이 아닙니다. 독립적인 백업 복원, 애플리케이션 드라이버 및 SQL 호환성을 먼저 테스트하십시오. 공식 릴리스 노트 

Note

이 문서는 처음에 Ubuntu 26.04 LTS 2026년 4월 릴리스 노트와 비교하여 확인되었습니다. 데이터베이스 버전 및 업그레이드 노트에는 여전히 페이지별 유효성 검사가 필요합니다.

데이터베이스는 거의 모든 웹 애플리케이션과 서비스의 핵심 구성 요소입니다. Ubuntu 공식 저장소는 널리 사용되는 많은 데이터베이스에 대한 설치 패키지를 제공합니다. 이 문서에서는 Ubuntu 26.04: MySQL/MariaDB, PostgreSQL, Redis 및 SQLite에서 가장 일반적으로 사용되는 데이터베이스를 설치하고 구성하는 방법을 다룹니다.

MySQL / MariaDB

MySQL은 세계에서 가장 인기 있는 오픈 소스 관계형 데이터베이스 중 하나이며, MariaDB은 MySQL의 원래 개발자가 관리하는 MySQL의 커뮤니티 포크입니다. 둘은 사용법에 있어 호환성이 매우 높습니다.

Tip

Ubuntu 26.04 공식 저장소는 MySQL와 MariaDB을 모두 제공합니다. MariaDB는 더 나은 성능 최적화와 보다 개방적인 커뮤니티 거버넌스를 갖춘 MySQL의 완벽하게 호환되는 드롭인 대체품입니다. 특별한 요구 사항이 없다면 MariaDB을 권장합니다. 명령줄 도구와 SQL 구문은 거의 동일합니다.

MySQL 설치 중

# Install MySQL Server sudo apt update sudo apt install mysql-server # Check service status sudo systemctl status mysql # Enable auto-start on boot sudo systemctl enable mysql

MariaDB 설치 중

# Install MariaDB Server sudo apt update sudo apt install mariadb-server # Check service status sudo systemctl status mariadb # Enable auto-start on boot sudo systemctl enable mariadb

보안 초기화

설치 후에는 보안 초기화 스크립트를 실행하여 데이터베이스를 강화해야 합니다.

# Both MySQL and MariaDB use the same command sudo mysql_secure_installation

스크립트는 다음 작업을 안내합니다.

  1. 루트 비밀번호 설정(아직 설정되지 않은 경우)
  2. 익명 사용자 제거(강력히 권장)
  3. 루트 원격 로그인을 허용하지 않음(강력히 권장)
  4. 테스트 데이터베이스 제거(권장)
  5. 권한 테이블 다시 로드

기본 작업

# Log in to MySQL/MariaDB (Ubuntu defaults to unix_socket authentication) sudo mysql # Or log in with a password mysql -u root -p

일반적인 SQL 작업:

-- List all databases SHOW DATABASES; -- Create a database CREATE DATABASE myapp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -- Use a database USE myapp; -- Create a user and set password CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'StrongPassword123!'; -- Grant privileges (limited to a specific database) GRANT ALL PRIVILEGES ON myapp.* TO 'appuser'@'localhost'; -- Flush privileges FLUSH PRIVILEGES; -- View user privileges SHOW GRANTS FOR 'appuser'@'localhost'; -- Create a table CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Insert data INSERT INTO users (username, email) VALUES ('zhang', 'zhang@example.com'); -- Query data SELECT * FROM users; -- View table structure DESCRIBE users; -- Drop a user DROP USER 'appuser'@'localhost'; -- Drop a database DROP DATABASE myapp; -- Exit EXIT;

원격 액세스 구성

기본적으로 MySQL/MariaDB은 localhost(127.0.0.1)에서만 수신 대기합니다. 원격 액세스를 활성화하려면:

# Edit MySQL configuration sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf # Or MariaDB configuration sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

bind-address 줄을 찾아 다음과 같이 변경합니다.

# Allow connections from all IPs (in production, bind to a specific IP) bind-address = 0.0.0.0

그런 다음 원격 연결을 허용하는 사용자를 만듭니다.

-- Create a user that can connect from any IP CREATE USER 'remoteuser'@'%' IDENTIFIED BY 'StrongPassword123!'; GRANT ALL PRIVILEGES ON myapp.* TO 'remoteuser'@'%'; FLUSH PRIVILEGES; -- Or restrict to a specific IP CREATE USER 'remoteuser'@'192.168.1.100' IDENTIFIED BY 'StrongPassword123!'; GRANT ALL PRIVILEGES ON myapp.* TO 'remoteuser'@'192.168.1.100'; FLUSH PRIVILEGES;
# Restart the service for changes to take effect sudo systemctl restart mysql # Or sudo systemctl restart mariadb # If the firewall is enabled, allow the port sudo ufw allow 3306/tcp
Warning

데이터베이스를 공용 인터넷(0.0.0.0)에 노출하는 것은 매우 위험합니다. 원격 액세스가 필요한 경우 강력한 비밀번호를 사용하고, 허용된 연결 IP를 제한하고, 방화벽 규칙을 구성하고, 포트를 직접 노출하는 대신 SSH 터널 또는 VPN 사용을 고려하십시오.

공통 구성 최적화

/etc/mysql/mysql.conf.d/mysqld.cnf(또는 해당 MariaDB 구성 파일)을 편집합니다.

[mysqld] # Character set (utf8mb4 recommended to support emoji and other characters) character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci # InnoDB buffer pool (recommended: 50%-70% of physical memory) innodb_buffer_pool_size = 1G # Maximum connections max_connections = 200 # Slow query log slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 2
# Restart the service after changes sudo systemctl restart mysql

PostgreSQL

PostgreSQL(일반적으로 PG로 약칭)은 엄격한 SQL 표준 준수, 풍부한 데이터 유형 및 강력한 확장성으로 알려진 강력한 오픈 소스 객체 관계형 데이터베이스입니다. 복잡한 쿼리, 지리공간 데이터(PostGIS) 및 JSON 데이터에 이상적인 선택입니다.

PostgreSQL 설치 중

# Install PostgreSQL sudo apt update sudo apt install postgresql postgresql-client # Check service status sudo systemctl status postgresql # Check installed version psql --version

사용자 및 데이터베이스 생성

PostgreSQL은 자체 사용자 인증 시스템을 사용합니다. 설치 후 postgres이라는 시스템 사용자 및 데이터베이스 수퍼유저가 자동으로 생성됩니다.

# Switch to the postgres user sudo -u postgres psql
-- Create a new database user CREATE USER appuser WITH PASSWORD 'StrongPassword123!'; -- Create a database and assign an owner CREATE DATABASE myapp OWNER appuser; -- Grant connection privileges GRANT ALL PRIVILEGES ON DATABASE myapp TO appuser; -- List all databases \l -- List all users \du -- Switch database \c myapp -- Exit \q

명령줄 도구를 사용할 수도 있습니다.

# Create a new user using the postgres account sudo -u postgres createuser --interactive appuser # Create a database sudo -u postgres createdb -O appuser myapp # Connect with the new user psql -U appuser -d myapp -h localhost

기본 작업

# Connect to a database psql -U appuser -d myapp -h localhost
-- Create a table CREATE TABLE articles ( id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, content TEXT, tags TEXT[], metadata JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Insert data (note: PostgreSQL supports array and JSON types) INSERT INTO articles (title, content, tags, metadata) VALUES ( 'Ubuntu 26.04 Released', 'The new version brings many improvements...', ARRAY['ubuntu', 'linux', 'release'], '{"author": "admin", "views": 0}'::jsonb ); -- Query data SELECT * FROM articles; -- JSON query SELECT title FROM articles WHERE metadata->>'author' = 'admin'; -- Array query SELECT title FROM articles WHERE 'ubuntu' = ANY(tags); -- View table structure \d articles -- List all tables \dt -- View table sizes \dt+

일반적인 psql 명령

명령설명
\l모든 데이터베이스 나열
\c dbname특정 데이터베이스로 전환
\dt현재 데이터베이스의 모든 테이블 나열
\d tablename테이블 구조 보기
\du모든 사용자/역할 나열
\di모든 인덱스 나열
\df모든 기능 나열
\timing쿼리 타이밍 켜기/끄기 전환
\x확장된 디스플레이 모드 전환
\q출구

원격 액세스 구성

# Edit the main configuration file sudo nano /etc/postgresql/18/main/postgresql.conf
# Change the listen address listen_addresses = '*'
# Edit the client authentication configuration sudo nano /etc/postgresql/18/main/pg_hba.conf

파일 끝에 추가하십시오.

# Allow a specific subnet via password authentication host all all 192.168.1.0/24 scram-sha-256 # Or allow all IPs (not recommended for production) host all all 0.0.0.0/0 scram-sha-256
# Restart PostgreSQL sudo systemctl restart postgresql # Allow through firewall sudo ufw allow 5432/tcp

레디스 / Valkey

Redis/Valkey는 데이터베이스, 캐시 및 메시지 브로커로 사용할 수 있는 오픈 소스 인 메모리 데이터 구조 저장소입니다. 문자열, 해시, 목록, 집합 등 다양한 데이터 구조를 지원하며 읽기/쓰기 속도가 매우 빠른 것으로 알려져 있습니다.

Note

Ubuntu 26.04 공식 저장소는 Valkey 9.0(Redis 프로토콜과 호환되는 Redis의 커뮤니티 포크)을 홍보하고 이를 main 구성 요소로 옮겼습니다. Valkey를 권장합니다. Redis는 여전히 별도로 설치할 수 있습니다. valkey-server과 redis-server가 저장소에 공존합니다. 아래 예에서는 valkey-server / valkey-cli 명령과 함께 Valkey를 사용합니다. 이전 redis-cli는 여전히 호환성 별칭으로 사용할 수 있습니다.

Valkey 설치

# Install Valkey (recommended on 26.04) sudo apt update sudo apt install valkey-server # If you need Redis, you can install it separately (coexists with Valkey; swap the redis prefix into the commands) # sudo apt install redis-server # Check service status sudo systemctl status valkey-server # Verify it is working properly valkey-cli ping # Should output: PONG

기본 작업

# Connect to the Valkey CLI (redis-cli is also available as a compatibility alias) valkey-cli
# String operations SET name "Ubuntu Fan" GET name # Set a key with expiration (60 seconds) SET session:abc123 "user_data" EX 60 # Check remaining TTL TTL session:abc123 # Hash operations (similar to objects) HSET user:1 name "John" email "john@example.com" age "30" HGET user:1 name HGETALL user:1 # List operations LPUSH tasks "task1" "task2" "task3" LRANGE tasks 0 -1 RPOP tasks # Set operations SADD online_users "user1" "user2" "user3" SMEMBERS online_users SISMEMBER online_users "user1" # Sorted set (leaderboard scenario) ZADD leaderboard 100 "player1" 200 "player2" 150 "player3" ZREVRANGE leaderboard 0 -1 WITHSCORES # List all keys KEYS * # Delete a key DEL name # Check key type TYPE user:1 # View server info INFO # View memory usage INFO memory # Exit QUIT

지속성 구성

데이터는 기본적으로 메모리에 저장되며 다시 시작하면 손실됩니다. Valkey는 두 가지 지속성 방법을 제공합니다.

RDB (Snapshots) — 주기적으로 메모리 내 데이터를 스냅샷 파일로 저장합니다.

# Edit Valkey configuration (the Redis-compatible package uses /etc/redis/redis.conf) sudo nano /etc/valkey/valkey.conf
# RDB persistence rules (enabled by default) # Save if at least 1 change in 3600 seconds save 3600 1 # Save if at least 100 changes in 300 seconds save 300 100 # Save if at least 10000 changes in 60 seconds save 60 10000 # RDB file location dir /var/lib/valkey dbfilename dump.rdb

AOF(Append-Only File) — 모든 쓰기 작업을 기록합니다.

# Enable AOF appendonly yes # AOF sync policy # always: Sync on every write (safest, but slowest) # everysec: Sync once per second (recommended, balances safety and performance) # no: Let the OS decide (fastest, but may lose data) appendfsync everysec # AOF filename appendfilename "appendonly.aof"
# Restart Valkey for changes to take effect sudo systemctl restart valkey-server

Valkey 보안 구성

sudo nano /etc/valkey/valkey.conf
# Set password requirepass YourStrongRedisPassword # Bind address (defaults to local access only) bind 127.0.0.1 ::1 # Disable dangerous commands rename-command FLUSHDB "" rename-command FLUSHALL "" rename-command CONFIG ""
# Connect with password valkey-cli -a YourStrongRedisPassword # Or authenticate after connecting valkey-cli AUTH YourStrongRedisPassword

SQLite

SQLite는 경량 임베디드 관계형 데이터베이스입니다. 별도의 서버 프로세스가 필요하지 않으며, 모든 데이터가 하나의 파일에 저장됩니다. SQLite는 소규모 애플리케이션, 프로토타입 제작, 모바일 앱 및 임베디드 시스템에 이상적입니다.

설치 및 사용법

# Install SQLite sudo apt install sqlite3 # Create/open a database file sqlite3 mydb.sqlite # Operate within the SQLite prompt
-- Create a table CREATE TABLE notes ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); -- Insert data INSERT INTO notes (title, content) VALUES ('Test Note', 'This is a test entry'); -- Query SELECT * FROM notes; -- List all tables .tables -- View table structure .schema notes -- Display results with column names .headers on .mode column -- Export as SQL .dump -- Export as CSV .mode csv .output notes.csv SELECT * FROM notes; .output stdout -- Exit .quit

SQLite의 장점은 구성 및 유지 관리가 필요 없다는 점입니다. 그것은 적합합니다:

  • 소규모 웹 애플리케이션(예: 개인 블로그)
  • 개발 및 테스트 환경
  • 데스크탑 애플리케이션을 위한 로컬 데이터 스토리지
  • 데이터 분석(Python의 sqlite3 모듈과 결합)

데이터베이스 백업 전략

데이터 백업은 데이터베이스 관리에서 가장 중요한 작업 중 하나입니다. 각 데이터베이스의 백업 방법은 다음과 같습니다.

MySQL / MariaDB 백업

# Back up a single database mysqldump -u root -p myapp > myapp_backup_$(date +%Y%m%d).sql # Back up all databases mysqldump -u root -p --all-databases > all_databases_$(date +%Y%m%d).sql # Compressed backup mysqldump -u root -p myapp | gzip > myapp_backup_$(date +%Y%m%d).sql.gz # Restore a database mysql -u root -p myapp < myapp_backup_20260324.sql # Restore a compressed backup gunzip < myapp_backup_20260324.sql.gz | mysql -u root -p myapp

PostgreSQL 백업

# Back up a single database sudo -u postgres pg_dump myapp > myapp_backup_$(date +%Y%m%d).sql # Back up all databases sudo -u postgres pg_dumpall > all_databases_$(date +%Y%m%d).sql # Custom format backup (supports parallel restore) sudo -u postgres pg_dump -Fc myapp > myapp_backup_$(date +%Y%m%d).dump # Restore SQL format backup sudo -u postgres psql myapp < myapp_backup_20260324.sql # Restore custom format backup sudo -u postgres pg_restore -d myapp myapp_backup_20260324.dump

발키 백업

# Manually trigger RDB snapshot valkey-cli BGSAVE # Copy the RDB file sudo cp /var/lib/valkey/dump.rdb /backup/valkey_$(date +%Y%m%d).rdb # Restore: stop Valkey, replace dump.rdb, restart sudo systemctl stop valkey-server sudo cp /backup/valkey_20260324.rdb /var/lib/valkey/dump.rdb sudo chown valkey:valkey /var/lib/valkey/dump.rdb sudo systemctl start valkey-server

자동 백업 스크립트

자동 백업을 위한 크론 작업을 만듭니다.

# Create backup script sudo nano /usr/local/bin/db-backup.sh
#!/bin/bash BACKUP_DIR="/backup/databases" DATE=$(date +%Y%m%d_%H%M%S) mkdir -p "$BACKUP_DIR" # MySQL/MariaDB backup mysqldump -u root --all-databases | gzip > "$BACKUP_DIR/mysql_$DATE.sql.gz" # PostgreSQL backup sudo -u postgres pg_dumpall | gzip > "$BACKUP_DIR/postgres_$DATE.sql.gz" # Valkey backup valkey-cli BGSAVE sleep 5 cp /var/lib/valkey/dump.rdb "$BACKUP_DIR/valkey_$DATE.rdb" # Delete backups older than 30 days find "$BACKUP_DIR" -type f -mtime +30 -delete echo "Backup complete: $DATE"
# Set execute permission sudo chmod +x /usr/local/bin/db-backup.sh # Add cron job (runs daily at 3 AM) sudo crontab -e # Add the following line: # 0 3 * * * /usr/local/bin/db-backup.sh >> /var/log/db-backup.log 2>&1

데이터베이스 비교: MySQL 대 PostgreSQL 대 MariaDB

특징MySQLPostgreSQLMariaDB
개발자신탁PostgreSQL 커뮤니티MariaDB 재단
특허GPL v2(이중 라이센스)PostgreSQL 라이센스(MIT와 유사)GPL v2
기본 포트330654323306
ACID 규정 준수InnoDB 엔진 지원전폭적인 지원InnoDB/Aria 엔진 지원
JSON 지원JSON 유형JSONB 유형(더 강력함)JSON 유형
전체 텍스트 검색지원됨지원됨(더 강력함)지원됨
지리공간기본 지원PostGIS 확장(업계 최고)기본 지원
복제기본 복제본, 그룹 복제스트리밍 복제, 논리적 복제기본 복제본, Galera 클러스터
스토리지 엔진다중(InnoDB, MyISAM 등)단발다중(InnoDB, Aria, ColumnStore 등)
SQL 표준 준수좋은최상의좋은
사용 사례웹 앱, 읽기 집약적인 워크로드복잡한 쿼리, 데이터 분석, GIS웹 앱, MySQL 대체
학습 곡선낮은중간낮음(MySQL 호환)

추천 가이드

  • MySQL: 가장 큰 생태계와 대부분의 커뮤니티 리소스. 대부분의 웹 애플리케이션에 적합
  • PostgreSQL: 가장 강력한 기능; 복잡한 쿼리, JSON 작업 및 지리공간 데이터에 이상적
  • MariaDB: 더욱 공격적인 성능 최적화와 보다 개방적인 커뮤니티를 갖춘 오픈 소스 MySQL 대안

일반 관리 명령 요약

# --- MySQL / MariaDB --- sudo systemctl start mysql # Start sudo systemctl stop mysql # Stop sudo systemctl restart mysql # Restart sudo systemctl status mysql # Check status sudo mysql # Log in # --- PostgreSQL --- sudo systemctl start postgresql # Start sudo systemctl stop postgresql # Stop sudo systemctl restart postgresql # Restart sudo systemctl status postgresql # Check status sudo -u postgres psql # Log in # --- Valkey --- sudo systemctl start valkey-server # Start sudo systemctl stop valkey-server # Stop sudo systemctl restart valkey-server # Restart sudo systemctl status valkey-server # Check status valkey-cli # Log in valkey-cli INFO # View info valkey-cli DBSIZE # View key count

올바른 데이터베이스를 선택하고 구성하는 것은 안정적인 웹 애플리케이션을 구축하는 데 필수적입니다. 프로젝트 요구 사항에 가장 적합한 데이터베이스를 찾으려면 개발 환경에서 다양한 데이터베이스를 실험해 보는 것이 좋습니다.