0
0
DockerHow-ToBeginner · 3 min read

How to Use Image in Docker Compose: Simple Guide

In docker-compose.yml, use the image key under a service to specify the Docker image to run. This can be an image from Docker Hub or a custom image you built locally.
📐

Syntax

The image key in docker-compose.yml defines which Docker image the service uses. It can include an image name and optionally a tag (version). If no tag is given, Docker uses latest by default.

  • image: The name of the Docker image, e.g., nginx or redis:6.2.
  • service name: The name you give to the container service.
yaml
version: '3.8'
services:
  service_name:
    image: image_name:tag
💻

Example

This example shows a simple docker-compose.yml file that runs an nginx web server using the official image from Docker Hub.

yaml
version: '3.8'
services:
  web:
    image: nginx:1.23
    ports:
      - "8080:80"
Output
Creating network "default" with the default driver Creating web_1 ... done # Access http://localhost:8080 in your browser to see the nginx welcome page.
⚠️

Common Pitfalls

Common mistakes when using image in Docker Compose include:

  • Forgetting to specify the image tag, which defaults to latest and may cause unexpected updates.
  • Using build and image keys incorrectly together; build is for building images locally, while image pulls from a registry.
  • Not exposing or mapping ports, so the service is not reachable from outside.
yaml
version: '3.8'
services:
  app:
    build: .
    image: myapp:latest

# Right way: Use either build or image alone or together carefully

version: '3.8'
services:
  app:
    build: .

# or

version: '3.8'
services:
  app:
    image: myapp:latest
📊

Quick Reference

Tips for using image in Docker Compose:

  • Always specify a tag to avoid surprises.
  • Use official images from Docker Hub when possible.
  • Map ports to access services externally.
  • Use docker-compose pull to update images before starting.

Key Takeaways

Use the image key in docker-compose.yml to specify which Docker image a service uses.
Always specify an image tag to control the exact version of the image.
Do not confuse image with build; image pulls images, build creates them locally.
Map ports in Compose to access your container services from outside.
Use official images from trusted sources to ensure stability and security.