Docker

How Does “docker-compose” Work for Detached Mode?

Docker compose is a well-known Docker utility that allows you to run and share multi-container applications and services. Its working is based on the relevant “.yml” file. The compose file contains instructions for configuring one or more containers to deploy the containerized application. It can also run and configure application containers in detached mode.

In this write-up, we will elaborate on how “docker-compose” works for detached mode.

How Does “docker-compose” Work for Detached Mode?

The detached mode runs the Docker container in the background and cannot get output or input. It also allows users to do any other task on the terminal without stopping the Docker container.

To run the Docker container in detached mode using “docker-compose”, go through the provided instructions.

Step 1: Create “docker-compose.yml” File
First, launch the Visual Studio Code editor and create a new “docker-compose.yml” file. Paste the given into the “docker-compose” file:

version: "alpine"
services:
  web:
    build: .
    ports:
      - "8080:8080"
  golang:
    image: "golang:alpine"

Step 2: Create Program File
Next, define the simple Golang program into the “main.go” file. To do so, paste the following code into the file:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func handler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello! Welcome to LinuxHint Tutorial")
}
func main () {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}

Step 3: Run Docker Compose Container at Background
Now, execute the “docker-compose up” command to build and execute containers in detached mode. Here, the “-d” option is specifically used to execute the container in detached mode:

> docker-compose up -d

Alternatively, users can also use the “–detach” option for running the container in the detached mode:

> docker-compose up --detach

After that, visit the “localhost:8080” URL on your browser:

Here, you can see we have executed the docker container in detached mode using “docker-compose”:

Conclusion

The “docker-compose” command supports the detach mode with the help of the “–detach” or “-d” option. To run the Docker container in detached mode or the background using “docker-compose”, utilize the “docker-compose up -d” command. This post has demonstrated how “docker-compose” works for detached mode.

About the author

Rafia Zafar

I am graduated in computer science. I am a junior technical author here and passionate about Programming and learning new technologies. I have worked in JAVA, HTML 5, CSS3, Bootstrap, and PHP.