Tushar Jain
Tushar Jain

Reputation: 83

MySql Setup in Linux Docker Container Via Terraform

Requirement: Need to automate MySQL installation & Database creation on Linux(Ubuntu)Docker Container via Terra form. I am doing all this stuff on my local machine & below is the Terra form configuration.

Terra form file:

resource "docker_container" "db-server1" {
  name  = "db-server"
  image = docker_image.ubuntu.latest
  ports {
    internal = 80
    external = 9093
  }

  provisioner "local-exec" {
      command = "docker container start dbs-my"
  }
  provisioner "local-exec" {
      command = "docker exec dbs-my apt-get update"
  }
  provisioner "local-exec" {
      command = "docker exec dbs-my apt-get -y install mysql-server"
  }
}

But in container there is no mysql service present, when i am trying to launch mysql command, i am getting below error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Upvotes: 3

Views: 2152

Answers (1)

David Maze
David Maze

Reputation: 159751

Using Terraform for this at all is a little unusual; you might look at more Docker-native tools like Docker Compose to set this up. There are also several anti-patterns in this example: you should generally avoid installing software in running containers, and avoid running long sequences of imperative commands via Terraform, and it's usually not useful to run the bare ubuntu Docker image as-is.

You can run the Docker Hub mysql image instead:

resource "docker_image" "mysql" {
  name = "mysql:8"
}

resource "random_password" "mysql_root_password" {
  length = 16
}

resource "docker_container" "mysql" {
  name = "mysql"
  image = "${docker_image.mysql.latest}"
  env {
    MYSQL_ROOT_PASSWORD = "${random_password.mysql_root_password.result}"
  }
  mounts {
    source = "/some/host/mysql/data/path"
    target = "/var/lib/mysql/data"
    type = "bind"
  }
  ports {
    internal = 3306
    external = 3306
  }
}

If you wanted to do further setup on the created database, you could use the MySQL provider

provider "mysql" {
  endpoint = "127.0.0.1:3306" # the "external" port
  username = "root"
  password = "${random_password.mysql_root_password.result}"
}

resource "mysql_database" "db" {
  name = "db"
}

Upvotes: 3

Related Questions