example-deployable-app/database.tf

63 lines
2.1 KiB
Terraform
Raw Normal View History

2024-06-14 02:18:48 +00:00
# Find our latest postgres 16 image
data "docker_registry_image" "postgres_quassel" {
name = "postgres:16"
}
# Generate a random password for our database
resource "random_password" "quassel_db_password" {
length = 32
special = false
}
# Create a volume for our database data to live in
resource "docker_volume" "quassel_db" {
name = "${var.docker_prefix}-quassel-db"
}
# Create our database service
resource "docker_service" "quassel_db" {
name = "${var.docker_prefix}-quassel-db"
task_spec {
container_spec {
# We've got our image from the registry...
image = "${data.docker_registry_image.postgres_quassel.name}@${data.docker_registry_image.postgres_quassel.sha256_digest}"
# And we're going to set some environment variables
env = {
POSTGRES_USER = local.pg_username
POSTGRES_DB = local.pg_database
POSTGRES_PASSWORD = local.pg_password
}
# We're going to define a nice healthcheck that will check that postgres is alive and well
healthcheck {
# Effectively this is running 'pg_isready -d postgres -U postgres' on the commandline inside the container and if it returns 0, the container is healthy, anything else is failure
test = ["CMD-SHELL", "pg_isready", "-d", local.pg_database, "-U", local.pg_username]
interval = "5s"
start_period = "15s"
}
# And we're going to mount our data volume to the container so that the data persists between restarts
mounts {
target = "/var/lib/postgresql/data"
type = "volume"
source = docker_volume.quassel_db.id
}
}
# And attach our network so that the quassel service can talk to the database
networks_advanced {
name = docker_network.quassel.id
}
}
# And we're going to wait for it to be up and running before we move on
converge_config {
delay = "5s" # Wait 5 seconds between checks
timeout = "2m" # Give up after 2 minutes
}
endpoint_spec {
ports {
target_port = local.pg_port_internal
published_port = local.pg_port_external
protocol = "tcp"
publish_mode = "ingress"
}
}
}