Skip to content

docker-compose-service-definition-structure

docker-compose-service-definition-structure refers to the schema used to define individual services within a docker-compose.yml file^[600-developer__docker__docker-compose__docker-compouse-02.md]. This structure encapsulates the configuration required to run a container image, including network settings, storage persistence, restart policies, and environment variables^[600-developer__docker__docker-compose__docker-compouse-02.md].

Configuration Example

The following example demonstrates the definition of a database service named db:

version: "3"
services:
  db:
    image: mysql:5.7
    ports:
      - "33060:3306"
    volumes:
      - ./data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_USER=tommy
      - MYSQL_PASSWORD=tommy
      - MYSQL_DATABASE=dockerDb
      - MYSQL_ROOT_PASSWORD=root
^[600-developer__docker__docker-compose__docker-compouse-02.md]

Common Directives

Image and Ports

The image directive specifies the container image to use (e.g., mysql:5.7). The ports mapping defines the port forwarding rules, publishing a container's port to the host^[600-developer__docker__docker-compose__docker-compouse-02.md].

Volumes

The volumes directive manages data persistence by mounting paths from the host machine into the container^[600-developer__docker__docker-compose__docker-compouse-02.md]. In the example above, ./data on the host is mapped to /var/lib/mysql inside the container.

Restart Policy

The restart policy controls the container's behavior upon exit or failure^[600-developer__docker__docker-compose__docker-compouse-02.md]. Setting this to always ensures that the service is automatically restarted if it stops or if the system reboots.

Environment Variables

The environment section allows for the injection of configuration variables into the container at runtime^[600-developer__docker__docker-compose__docker-compouse-02.md]. This is commonly used for setting passwords, user names, or application-specific settings.

  • [[docker]]
  • [[volumes]]
  • [[environment-variables]]

Sources