DOCKER-7
DOCKER-7
DOCKER-7
Key Concepts
python
import psycopg2
import os
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
cur = conn.cursor()
@app.route('/')
def hello():
result = cur.fetchone()
return result[0]
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Explanation
Step 2: Dockerfile
dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt ./
COPY . .
EXPOSE 5000
Explanation
● FROM python:3.11-slim: Uses a lightweight Python image.
● COPY: Copies the necessary files into the container.
● RUN pip install: Installs the required Python packages.
● CMD: Runs the Flask app when the container starts.
The line cur = conn.cursor() in the code creates a cursor object, which is used to
interact with the PostgreSQL database. Here's a detailed explanation:
What is a Cursor?
A cursor is a pointer that allows you to execute SQL queries and retrieve results
from the database. It acts as an intermediary between your Python code and the
database, enabling you to send SQL commands and fetch data.
How It Works:
● conn: This is the connection object, which represents the connection to the
PostgreSQL database. It is created by calling
psycopg2.connect(DATABASE_URL).
● cursor(): This method is called on the connection object (conn) to create a
cursor. The cursor is used to execute SQL queries, fetch results, and manage
database transactions.
● Execute SQL Queries: You use the cursor to send SQL commands (like
SELECT, INSERT, UPDATE, etc.) to the database.
● Fetch Data: After executing a query, the cursor allows you to retrieve the
results of that query.
Flask
psycopg2-binary
Explanation
yaml
version: "3.8"
services:
web:
build: .
ports:
- "5000:5000"
environment:
- DATABASE_URL=postgresql://user:password@db:5432/mydatabase
depends_on:
- db
db:
image: postgres:15
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydatabase
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Explanation
docker-compose up --build
docker-compose down
Conclusion
This project shows how to create a Python Flask app, connect it to PostgreSQL,
and run both inside Docker containers using Docker Compose. It's a great way to
manage and deploy web applications in isolated environments.
By the end of this tutorial, you'll have a running Node.js app connected to
MongoDB, both running in Docker containers.
app.js
javascript
// Connect to MongoDB
mongoose
.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('MongoDB connection error:', err));
Explanation:
Dockerfile
dockerfile
# Install dependencies
RUN npm install
Explanation:
Step 3: package.json
package.json
json
{
"name": "node-mongo-docker",
"version": "1.0.0",
"description": "Node.js app with MongoDB using Docker",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.5.1"
}
}
Explanation:
Use Docker Compose to define and manage the Node.js and MongoDB containers.
docker-compose.yml
yaml
version: "3.8"
services:
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- MONGO_URI=mongodb://db:27017/mydatabase
depends_on:
- db
db:
image: mongo:6
container_name: mongo
ports:
- "27017:27017"
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Explanation:
docker-compose up --build
1. This command:
○ Builds the Docker image for the Node.js app.
○ Starts both the Node.js app and MongoDB containers.
○ Maps ports 3000 (Node.js) and 27017 (MongoDB) for external access.
2. Access the Application: Open your browser and navigate to
http://localhost:3000. You should see the message: Hello, Node.js with
MongoDB!.
docker-compose down
Conclusion
This guide demonstrates how to set up a Node.js application with MongoDB using
Docker and Docker Compose. The containers ensure a consistent and portable
development environment, making it easy to deploy the application across different
systems.
src/main/java/com/example/demo/DemoApplication.java
java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(DemoApplication.class, args);
Application Configuration
src/main/resources/application.properties
properties
spring.datasource.url=jdbc:mysql://db:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.port=8080
2. Maven Configuration
pom.xml
xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
3. Dockerfile
Dockerfile
dockerfile
FROM openjdk:17
WORKDIR /app
docker-compose.yml
yaml
version: "3.8"
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
environment:
- SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/mydatabase
- SPRING_DATASOURCE_USERNAME=root
- SPRING_DATASOURCE_PASSWORD=root
depends_on:
- db
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: mydatabase
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
5. Maven Wrapper
Ensure the Maven wrapper files (mvnw, .mvn/) are included in the project for
building the application inside the container.
Run the following command in the project directory to build and start the
containers:
docker-compose up --build
This command will build the application and start the containers.
Once the containers are running, you can access the application at:
● Application Logs: Check the logs to ensure the application connects to the
database successfully.
● Database Connection: Use a database client (e.g., MySQL Workbench) to
verify the MySQL database.
Conclusion
This project demonstrates the integration of a Java Spring Boot application with a
MySQL database in a containerized environment. It provides a scalable and
portable setup for modern Java development, ensuring consistency across
development, testing, and production environments.
Key Features:
Project Structure:
css
rust-todo-app/
├── Dockerfile
├── docker-compose.yml
├── Cargo.toml
├── src/
│ ├── main.rs
│ ├── db.rs
│ ├── models.rs
│ └── routes.rs
Step-by-Step Implementation
This file manages the dependencies for the Rust project. Add the necessary
dependencies for PostgreSQL and Actix-web (a web framework).
toml
[package]
name = "rust-todo-app"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4.0" # Web framework for handling HTTP requests
actix-rt = "2.6" # Runtime for Actix
serde = { version = "1.0", features = ["derive"] } # For serializing and
deserializing data
serde_json = "1.0" # For working with JSON
tokio = { version = "1", features = ["full"] } # Async runtime
deadpool-postgres = "0.9" # Connection pool for PostgreSQL
tokio-postgres = "0.7" # PostgreSQL client
This file sets up the Actix-web server and configures the routes.
rust
mod db;
mod models;
mod routes;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv().ok(); // Load environment variables from .env file
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(db_pool.clone())) // Share database pool across
requests
.configure(routes::init) // Set up routes
})
.bind(("0.0.0.0", 8080))? // Listen on all interfaces, port 8080
.run()
.await
}
This file manages the connection to the PostgreSQL database using the
deadpool-postgres library.
rust
rust
#[derive(Serialize, Deserialize)]
pub struct Task {
pub id: i32,
pub title: String,
pub completed: bool,
}
This file defines the routes for getting and creating tasks.
rust
#[post("/tasks")]
async fn create_task(db_pool: web::Data<Pool>, task: web::Json<Task>) -> impl
Responder {
HttpResponse::Created().finish() // Placeholder response
}
This Dockerfile builds and runs the Rust app inside a container.
dockerfile
WORKDIR /app
RUN apt-get update && apt-get install -y libssl-dev ca-certificates && rm -rf
/var/lib/apt/lists/*
WORKDIR /app
EXPOSE 8080
CMD ["./rust-todo-app"]
yaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
depends_on:
- db
environment:
DATABASE_URL: "postgres://user:password@db:5432/mydatabase"
volumes:
- ./src:/app/src
command: ["./rust-todo-app"]
db:
image: postgres:15
container_name: postgres_db
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: mydatabase
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
Running the Application with Docker
To build and start the application using Docker, run the following command:
docker-compose up --build
Once the containers are up and running, you can access the API at
http://localhost:8080.
This project provides a basic structure for a Rust web app with PostgreSQL,
allowing users to manage tasks with full CRUD functionality. It is also
containerized with Docker for easy deployment.
Key Features:
arduino
php-crud-app/
├── Dockerfile
├── docker-compose.yml
├── index.php
├── create.php
├── update.php
├── delete.php
├── db.php
├── config.php
├── .env
└── sql/
└── init.sql
Create (create.php)
php
<?php
include('db.php');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create User</title>
</head>
<body>
<h1>Create User</h1>
<form action="create.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required><br><br>
Read (index.php)
php
<?php
include('db.php');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Users</title>
</head>
<body>
<h1>Users List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td>
<a href="update.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a href="delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php } ?>
</table>
<a href="create.php">Create New User</a>
</body>
</html>
Update (update.php)
php
<?php
include('db.php');
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = $id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update User</title>
</head>
<body>
<h1>Update User</h1>
<form action="update.php?id=<?php echo $row['id']; ?>" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="<?php echo
$row['name']; ?>" required><br><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" value="<?php echo
$row['email']; ?>" required><br><br>
php
<?php
include('db.php');
if (isset($_GET['id'])) {
$id = $_GET['id'];
mysqli_close($conn);
?>
php
<?php
$servername = getenv('MYSQL_HOST');
$username = getenv('MYSQL_USER');
$password = getenv('MYSQL_PASSWORD');
$dbname = getenv('MYSQL_DB');
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
4. Create Dockerfile
This Dockerfile sets up the PHP environment with Apache and MySQL support.
dockerfile
This Docker Compose file sets up both the PHP web application and the MySQL
database.
yaml
version: "3.8"
services:
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "80:80"
environment:
- MYSQL_HOST=db
- MYSQL_USER=root
- MYSQL_PASSWORD=root
- MYSQL_DB=mydatabase
depends_on:
- db
db:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: mydatabase
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
sql
USE mydatabase;
docker-compose up --build
1. Access the Application: Once the containers are up and running, open your
browser and go to http://localhost. You should see the list of users (which
will be empty initially).
2. Create a New User: Click on "Create New User" to add a new user to the
database.
3. Edit or Delete a User: You can edit or delete users by clicking the
respective links next to each user in the list.
Check the Database: You can verify that the data has been inserted into the
database by accessing the MySQL container and running the following query:
sql
This project provides a complete CRUD application with PHP and MySQL,
demonstrating how to use Docker to containerize both the PHP application and the
MySQL database.