Write down Docker-Compose file for python flask and MySQL application.

Write down Docker-Compose file for python flask and MySQL application.

Here's a sample Docker Compose file (docker-compose.yml) for a Python Flask app using a MySQL database. This example is for a Flask app that connects to a MySQL database.

version: '3'

services:
  web:
    build: ./app
    ports:
      - "5000:5000"
    depends_on:
      - db
    environment:
      - MYSQL_HOST=db
      - MYSQL_PORT=3306
      - MYSQL_USER=myuser
      - MYSQL_PASSWORD=mypassword
      - MYSQL_DB=mydatabase

  db:
    image: mysql:8.0
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_DATABASE: mydatabase
      MYSQL_USER: myuser
      MYSQL_PASSWORD: mypassword
    ports:
      - "3306:3306"

In this example:

  • The web service is the Flask application. It builds the application using the Dockerfile in the ./app directory. The service exposes port 5000 on the host, and it depends on the db service.

  • The db service uses the official MySQL 8.0 image from the Docker Hub. It sets up the MySQL root password, creates a database (mydatabase), and creates a MySQL user (myuser) with a password (mypassword).

  • The Flask application is configured to connect to the MySQL database using environment variables (MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB). These environment variables are set to the corresponding values of the db service.

Here is a simplified directory structure for this example:

/myapp
|-- app
|   |-- Dockerfile
|   `-- app.py
|-- docker-compose.yml
|-- requirements.txt

Make sure to replace the placeholder values for passwords and other sensitive information with your actual configuration. Additionally, the Flask application (app.py) should be set up to connect to the MySQL database using the provided environment variables.

For the Flask application's Dockerfile (./app/Dockerfile), you might have something like this:

FROM python:3.9

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "app.py"]

This Dockerfile installs the dependencies listed in requirements.txt and copies the application code into the image.

After creating these files, you can build and run the services using the following commands:

docker-compose up --build

This will build and start the services. Access your Flask application at http://localhost:5000. To stop and remove the containers, use:

docker-compose down

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!