This write-up will illustrate how the “docker-compose” works in Docker.
How Does “docker-compose” Work in Docker?
“docker-compose” works with the “docker-compose.yml” file. The compose file includes instructions for building and starting a Docker container to deploy an application.
To use “docker-compose” for project development, launch the Visual Studio Code editor, open the project directory, and follow the given instructions.
Step 1: Create “docker-compose.yml” File
First, create a simple “docker-compose.yml” file that will create a “golang:alpine” image to build and start the Docker container. For this purpose, paste the instructions into the file:
services:
web:
build: .
ports:
- "8080:8080"
golang:
image:"golang:alpine"
Step 2: Create Program File
Next, create a “main.go” program file and paste the mentioned code in the file:
import (
"fmt"
"log"
"net/http"
)
funchandler (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello! Welcome to LinuxHint Tutorial")
}
funcmain () {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}
Step 3: Start Docker Compose
Now, start “docker-compose” to build and execute the container to deploy the “Golang” program:
Visit the “http:\\localhost:8080” in the browser:
It can be observed that we have successfully deployed the Golang program through “docker-compose”.
How to Run Docker Compose Containers in the Background?
Docker compose also supports different options to function differently. In order to run the container in the background, utilize the “–detach” or “-d” option:
How to Create a Container Only Without Starting it up?
Users can use the “docker-compose” command to construct a container without starting it. For this purpose, the “–no-start” option is used:
How to Recreate a Container Using Docker Compose?
To recreate a container rather than building a new one, use the “docker-compose” command with the “–force-recreate” option:
In order to start the container without recreating it, go through the provided command along with the “–no-recreate” option:
That was all about working of the “docker-compose” command in Docker.
Conclusion
The “docker-compose” command works with a compose format file. To use this command in Docker, first, create a new “docker-compose.yml” file. Then, utilize the “docker-compose up” command to run and build the container. The “docker-compose” command also uses different options to behave differently, such as “-d”, “–no-recreate”, “–force-recreate”, and “build”. This write-up has demonstrated how “docker-compose” works in Docker.