Installing nginx in a Docker Container using Terraform on macOS

This article shows how to install and configure nginx in a Docker container using Terraform on macOS. We are going to bind a host volume to the docker container so that we do not lose the web content when we destroy the nginx container.

The instructions for doing this differ slightly for macOS versus Linux.

First of all we need to go into Docker settings and click on Resources. This will expand and File Sharing will now be visible. Click on this and add a new directory to the file sharing resources so that we can bind mount a host directory into Docker containers. In the screen shot below you can see that I have added /Users/mark/devops to the resources. After you add a new file sharing resource you will need to Apply & Restart.

We are now ready to create the nginx Terraform configuration file. The coniguration I created can be seen below: –


provider "docker" {
  host = "unix:///var/run/docker.sock"

# Create NGINX container
resource "docker_container" "nginx" {
  image = "${docker_image.nginx.latest}"
  name  = "nginx"
  ports {
    internal = 80
    external = 80
  volumes {
    container_path  = "/usr/share/nginx/html"
    host_path  = "/Users/mark/devops/volumes/nginx/html"
    read_only = true

resource "docker_image" "nginx" {
  name = "nginx:latest"

Note the volumes section where I map the html content directory (container_path) to a directory on my local machine (host_path). In the host path (/Users/mark/devops/volumes/nginx/html) I created a custom index.html file so that I could test that the binding worked.

Issue the following commands to deploy the container (my configuration file is in a directory called nginx): –

terraform init nginx
terraform plan nginx
terraform apply --auto-approve nginx

If you already have an image called nginx running in docker you will need to stop it and destroy it first.

To check the install and binding have worked visit localhost in your browser:

You can destroy the container when you are finished testing by issuing the following command: –

terraform destroy nginx