How to install docker and terraform on ubuntu 20.04
Today Docker is quite popular on service deployment. While using Terraform, we can have infra as code to make deployment more efficient.
On ubuntu 20.04, we could have docker and terraform installed easily. Just follow the steps below.
Install Docker
First add the GPG key for the official Docker repository to your system.
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
Then add the Docker repository to APT sources.
$ sudo add-apt-repository "deb [arch=$(dpkg --print-architecture)] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
Update the repository.
$ sudo apt update
Finally install the Docker package.
$ sudo apt install docker-ce
You can check docker's running status by this command.
$ sudo systemctl status docker
It's better to add your linux account to docker group to avoid sudo for running docker.
$ sudo usermod -aG docker ${USER}
Then exit current shell and re-login to make the change above take effect.
The last step, run a docker demo to see if it's going fine.
$ docker run hello-world
Install Terraform
First, download and add the HashiCorp signed gpg keys to your system.
$ curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
Next, add the HashiCorp repository to the APT source.
$ sudo add-apt-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
Update the repository.
$ sudo apt update
Finally, install the program Terraform.
$ sudo apt install terraform
Once Terraform has been installed, verify its version.
$ terraform -v
Terraform v1.3.6
on linux_amd64
Run docker via terraform
We can create a terraform script to run docker as follows.
First create a project dir.
$ mkdir terraform
$ cd terraform
Create the script below, name it "main.tf".
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 2.13.0"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.latest
name = "tutorial"
ports {
internal = 80
external = 8000
}
}
Initialize the project, which downloads a plugin that allows Terraform to interact with Docker.
$ terraform init
Provision the NGINX server container with apply.
$ terraform apply
Verify the existence of the NGINX container by visiting hostname:8000 in your web browser.
And docker ps will show that,
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1b789f59a4d7 ac8efec875ce "/docker-entrypoint.…" 47 minutes ago Up 47 minutes 0.0.0.0:8000->80/tcp tutorial
To stop the container, run the following command in project dir.
$ terraform destroy
Now, you have implemented docker and terraform successfully on ubuntu 20.04.
References
How To Install and Use Docker on Ubuntu 20.04