Write down Docker Compose file for Rust  and MySQL application

Write down Docker Compose file for Rust and MySQL application

Docker Compose file for a Rust app with a MySQL database. This example is for when you have a Rust app in a folder called rust_app with a Cargo.toml file, and you want to link it to a MySQL database.


version: '3'
      context: ./rust_app
      - mysql
      - "8080:8080"
      - DATABASE_URL=mysql://root:password@mysql:3306/mydatabase
      - my_network

    image: mysql:8.0
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: mydatabase
      - "3306:3306"
      - my_network

    driver: bridge

In this Docker Compose file:

  • The rust_app service makes the Rust app using the Dockerfile in the ./rust_app folder. It depends on the mysql service, and the app's HTTP port 8080 is linked to the host.

  • The mysql service uses the official MySQL 8.0 image and sets environment variables for the root password and the database to be created.

  • The networks part creates a custom bridge network called my_network. This lets the Rust app and the MySQL service talk to each other.

Dockerfile (inside the ./rust_app directory):

# Use the official Rust image as the base image
FROM rust:latest

# Set the working directory

# Copy the application code into the container
COPY . .

# Build the Rust application
RUN cargo build --release

# Expose the port on which the Rust application will run

# Run the Rust application
CMD ["target/release/your_rust_app_binary"]

Change your_rust_app_binary to the real binary name from your Rust application. Also, remember to update the DATABASE_URL environment variable in the docker-compose.yml file so it matches your MySQL connection information.

To use this Docker Compose setup:

  1. Place the docker-compose.yml file in the root directory of your project.

  2. Create a Dockerfile in the ./rust_app directory with the content above.

  3. Run the following commands in the terminal:

     docker-compose up

This will create and start both the Rust app and the MySQL database containers. Visit your Rust app at http://localhost:8080. The app will connect to the MySQL database set in the DATABASE_URL environment variable.

Did you find this article valuable?

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