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.
docker-compose.yml:
version: '3'
services:
rust_app:
build:
context: ./rust_app
depends_on:
- mysql
ports:
- "8080:8080"
environment:
- DATABASE_URL=mysql://root:password@mysql:3306/mydatabase
networks:
- my_network
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: mydatabase
ports:
- "3306:3306"
networks:
- my_network
networks:
my_network:
driver: bridge
In this Docker Compose file:
The
rust_app
service makes the Rust app using theDockerfile
in the./rust_app
folder. It depends on themysql
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 calledmy_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
WORKDIR /app
# 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
EXPOSE 8080
# 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:
Place the
docker-compose.yml
file in the root directory of your project.Create a
Dockerfile
in the./rust_app
directory with the content above.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.