Skip to content

feature: added support for running sample code using Docker and docke… #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,6 @@ htmlcov/
coverage.xml
*.cover

# dotenv environment files
.env.local
.env.*
.env
!.env.example

# Ignore generated files and backups
*.orig
*.rej
Expand All @@ -82,3 +76,15 @@ public/
# Ignore personal notes or drafts
private-notes/
drafts/

# Docker
.docker-env
.docker-cache
docker-compose.override.yml

# Environment variables
.env.local
.env.*
.env
!.env.example
docker/environments/databases/.env
48 changes: 48 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
.PHONY: build run-snippet help db-start db-stop db-run-snippet

help:
@echo "Tech Notes Hub Docker Environment"
@echo "================================="
@echo ""
@echo "Usage:"
@echo " make build Build all Docker environments"
@echo " make run-snippet FILE=path Run a specific code snippet"
@echo " make db-start DB=type Start a specific database (mysql, postgres, mongodb, redis, sqlite)"
@echo " make db-stop DB=type Stop a specific database"
@echo " make db-run-snippet DB=type FILE=path Run a code snippet with database connection"
@echo " make help Show this help message"

build:
docker-compose build

run-snippet:
@if [ -z "$(FILE)" ]; then \
echo "Error: Please specify a file path. Example: make run-snippet FILE=snippets/algorithms/graph-traversal/graph_traversal.py"; \
exit 1; \
fi
./docker/run-snippet.sh $(FILE)

db-start:
@if [ -z "$(DB)" ]; then \
echo "Error: Please specify a database type. Example: make db-start DB=mysql"; \
exit 1; \
fi
docker-compose -f docker/environments/databases/docker-compose.yml up -d $(DB)

db-stop:
@if [ -z "$(DB)" ]; then \
echo "Error: Please specify a database type. Example: make db-stop DB=mysql"; \
exit 1; \
fi
docker-compose -f docker/environments/databases/docker-compose.yml stop $(DB)

db-run-snippet:
@if [ -z "$(DB)" ]; then \
echo "Error: Please specify a database type. Example: make db-run-snippet DB=mysql FILE=path/to/file.py"; \
exit 1; \
fi
@if [ -z "$(FILE)" ]; then \
echo "Error: Please specify a file path. Example: make db-run-snippet DB=mysql FILE=path/to/file.py"; \
exit 1; \
fi
./docker/run-db-snippet.sh $(DB) $(FILE)
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ Simply browse the folders or use GitHub's search feature to find the topic or pa

**For a complete table of contents with all available notes and resources, check out the [SUMMARY.md](SUMMARY.md) file.**

### 🐳 Docker Environments

This repository includes Docker configurations for running code snippets in various programming languages. To run a code snippet:

```bash
./docker/run-snippet.sh snippets/path/to/your/snippet.py
```

For more information on Docker usage, see the [Docker README](docker/README.md).

## 🤝 Contribution

Contributions are highly welcome! If you want to:
Expand Down
10 changes: 10 additions & 0 deletions README_vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ Mỗi ghi chú đều độc lập, bao gồm lý thuyết và mã ví dụ th

**Để xem danh mục đầy đủ với tất cả các ghi chú và tài nguyên có sẵn, hãy xem file [SUMMARY.md](SUMMARY.md).**

### 🐳 Môi Trường Docker

Kho lưu trữ này bao gồm cấu hình Docker để chạy đoạn mã trong nhiều ngôn ngữ lập trình khác nhau. Để chạy một đoạn mã:

```bash
./docker/run-snippet.sh snippets/path/to/your/snippet.py
```

Để biết thêm thông tin về cách sử dụng Docker, hãy xem [Docker README](docker/README_vi.md).

## 🤝 Đóng góp

Mọi đóng góp đều rất hoan nghênh! Nếu bạn muốn:
Expand Down
112 changes: 112 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
version: '1.0'

services:
# Python environment
python:
build:
context: .
dockerfile: docker/environments/python/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["--version"]

# JavaScript/Node.js environment
javascript:
build:
context: .
dockerfile: docker/environments/javascript/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["--version"]

# Java environment
java:
build:
context: .
dockerfile: docker/environments/java/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["/bin/bash", "-c", "java -version"]

# C/C++ environment
cpp:
build:
context: .
dockerfile: docker/environments/cpp/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["/bin/bash", "-c", "g++ --version"]

# Go environment
go:
build:
context: .
dockerfile: docker/environments/go/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["version"]

# Rust environment
rust:
build:
context: .
dockerfile: docker/environments/rust/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["/bin/bash", "-c", "rustc --version"]

# PHP environment
php:
build:
context: .
dockerfile: docker/environments/php/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["--version"]

# C# environment
csharp:
build:
context: .
dockerfile: docker/environments/csharp/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["/bin/bash", "-c", "dotnet --version"]

# Ruby environment
ruby:
build:
context: .
dockerfile: docker/environments/ruby/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["--version"]

# Shell environment for Linux and DevOps scripts
shell:
build:
context: .
dockerfile: docker/environments/shell/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["-c", "echo 'Shell environment ready'"]

# Databricks/PySpark environment
databricks:
build:
context: .
dockerfile: docker/environments/databricks/Dockerfile
volumes:
- ./snippets:/app/snippets
working_dir: /app
command: ["--version"]
158 changes: 158 additions & 0 deletions docker/DATABASE_GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Database Usage Guide with Docker

This guide helps you run code snippets with connections to databases in Docker environments.

## Supported Databases

- **MySQL** (8.0)
- **PostgreSQL** (15)
- **MongoDB** (6)
- **Redis** (7)
- **SQLite** (3.x)

## How to Use

### 1. Start a Specific Database

```bash
# Using Docker Compose directly
docker-compose -f docker/environments/databases/docker-compose.yml up -d mysql

# Or using the Makefile
make db-start DB=mysql
```

Valid values for DB are: `mysql`, `postgres`, `mongodb`, `redis`, `sqlite`

### 2. Run a Code Snippet with Database Connection

```bash
# Using the script directly
./docker/run-db-snippet.sh mysql snippets/databases/mysql_example.py

# Or using the Makefile
make db-run-snippet DB=mysql FILE=snippets/databases/mysql_example.py
```

### 3. Stop a Database When Not in Use

```bash
# Using Docker Compose directly
docker-compose -f docker/environments/databases/docker-compose.yml stop mysql

# Or using the Makefile
make db-stop DB=mysql
```

## Database Connection Information

When running a code snippet with a database, the following environment variables will be automatically passed to the container:

- `DB_HOST`: Database hostname
- `DB_PORT`: Database port
- `DB_USER`: Username for connection
- `DB_PASS`: Password for connection
- `DB_NAME`: Database name
- `DB_CONN_STR`: Full connection string

### Default Connection Strings

- **MySQL**: `mysql://user:password@tech-notes-mysql:3306/tech_notes`
- **PostgreSQL**: `postgresql://user:password@tech-notes-postgres:5432/tech_notes`
- **MongoDB**: `mongodb://user:password@tech-notes-mongodb:27017/tech_notes`
- **Redis**: `redis://tech-notes-redis:6379`
- **SQLite**: `sqlite:///data/tech_notes.db`

### Environment Variables Configuration

To change the default connection information, you can create a `.env` file in the `docker/environments/databases/` directory:

1. Copy the `.env.example` file to `.env`:
```bash
cp docker/environments/databases/.env.example docker/environments/databases/.env
```

2. Edit the `.env` file to change the connection information (usernames, passwords, database names, etc.)

3. When running the `run-db-snippet.sh` command or `make db-run-snippet`, the environment variables from the `.env` file will be automatically used.

Note: The `.env` file has been added to `.gitignore` to prevent it from being tracked by Git, ensuring sensitive information is not pushed to the repository.

## Example Connection Code

### Python with MySQL

```python
import os
import mysql.connector

# Get connection info from environment variables
db_host = os.environ.get('DB_HOST', 'localhost')
db_port = os.environ.get('DB_PORT', '3306')
db_user = os.environ.get('DB_USER', 'user')
db_pass = os.environ.get('DB_PASS', 'password')
db_name = os.environ.get('DB_NAME', 'tech_notes')

# Connect to the database
conn = mysql.connector.connect(
host=db_host,
port=db_port,
user=db_user,
password=db_pass,
database=db_name
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()

for user in users:
print(user)

conn.close()
```

### JavaScript with MongoDB

```javascript
const { MongoClient } = require('mongodb');

// Get connection string from environment variable
const uri = process.env.DB_CONN_STR || 'mongodb://user:password@localhost:27017/tech_notes';

async function main() {
const client = new MongoClient(uri);

try {
await client.connect();
const database = client.db('tech_notes');
const users = database.collection('users');

const query = {};
const cursor = users.find(query);

if ((await cursor.count()) === 0) {
console.log("No documents found!");
}

await cursor.forEach(user => {
console.log(user);
});

} finally {
await client.close();
}
}

main().catch(console.error);
```

## Sample Data

Each database has been configured with the following sample data:

- `users` table/collection with 3 users
- `posts` table/collection with 4 posts linked to users

You can see the details of the sample data in the init files in the respective directory of each database.

Loading