Skip to content
Snippets Groups Projects
Commit 486d8e7b authored by francisc.mendonca's avatar francisc.mendonca
Browse files

Updated everything

parent 4e59ba02
No related branches found
No related tags found
No related merge requests found
# Docker Compose Example
# Docker Container Basics: Understanding Bridge and Overlay Networks
## Objectives
- Learn the differences between **Bridge** and **Overlay** networks in Docker.
- Understand how containers in different networks can communicate.
## Getting started
## Introduction to Docker Networks
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Docker networks allow containers to communicate with each other. There are different types of networks, but we'll focus on two:
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
1. **Bridge Network:** Works on a single Docker host (your computer or server). Containers in the same bridge network can communicate, while those in different bridge networks need some special setup to talk to each other.
## Add your files
2. **Overlay Network:** Designed for Docker Swarm, which allows containers on different physical or virtual machines to communicate as if they are on the same network.
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
### When to Use Each Network
```
cd existing_repo
git remote add origin https://gitedu.hesge.ch/lsds/teaching/master/cloud/docker-compose-example.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitedu.hesge.ch/lsds/teaching/master/cloud/docker-compose-example/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
- **Bridge Network:** Use this when all your containers are on the same machine.
- **Overlay Network:** Use this when your containers are spread across multiple machines (in a Docker Swarm).
***
Now, let's look at some examples to make this clearer.
# Editing this README
## Example 1: Using a Bridge Network
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
In this example, we’ll set up a simple application with three containers: one RabbitMQ service and two other services (app1 and app2). We'll connect these services using two separate bridge networks.
## Suggestions for a good README
### Bridge Network Docker Compose File
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
Here’s the `docker-compose.yaml` file for setting up our containers:
## Name
Choose a self-explaining name for your project.
```yaml
version: '3.8'
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
services:
rabbitmq:
image: rabbitmq:3-management
container_name: rabbitmq
ports:
- "5672:5672" # RabbitMQ default messaging port
- "15672:15672" # RabbitMQ management console
networks:
- app-network-1
- app-network-2
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
app1:
image: franciscomendonca/auto-messaging:1.0.1
restart: on-failure
environment:
- START_WITH_MESSAGE=true # Start by sending a message
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-1
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
app2:
image: franciscomendonca/auto-messaging:1.0.1
container_name: app2
restart: on-failure
environment:
- START_WITH_MESSAGE=false # Wait for a message before responding
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-2
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
networks:
app-network-1:
driver: bridge
attachable: true
app-network-2:
driver: bridge
attachable: true
```
## License
For open source projects, say how it is licensed.
### Running the Bridge Network Example
1. Save the above YAML code in a file named `docker-compose.yaml`.
2. Open your terminal and navigate to the directory containing `docker-compose.yaml`.
3. Run the following command to start the services:
```bash
docker-compose up -d
```
4. To check if everything is running smoothly, use:
```bash
docker ps
```
5. To see logs for any service (e.g., `app1`):
```bash
docker logs app1
```
This setup allows `app1` and `app2` to communicate with `rabbitmq` because they are attached to networks (`app-network-1` and `app-network-2`). However, since they are on different bridge networks, they can't directly communicate with each other unless we set up additional network rules.
## Example 2: Using an Overlay Network in Docker Swarm
### What Is an Overlay Network?
An overlay network allows containers to communicate across different machines (nodes) in a Docker Swarm. You can think of it as a virtual network that spans across multiple Docker hosts.
### Prerequisites for Overlay Networks
You need a Docker Swarm cluster with at least three virtual machines (VMs). Let’s call them **VM1**, **VM2**, and **VM3**. You can use cloud services (like AWS or Azure) or local VMs.
### Overlay Network Docker Compose File
Here’s the `docker-compose.yaml` for the overlay network setup:
```yaml
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3-management
container_name: rabbitmq
ports:
- "5672:5672" # RabbitMQ default messaging port
- "15672:15672" # RabbitMQ management console
networks:
- app-network-1
- app-network-2
app1:
image: franciscomendonca/auto-messaging:1.0.1
restart: on-failure
environment:
- START_WITH_MESSAGE=true # Start by sending a message
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-1
app2:
image: franciscomendonca/auto-messaging:1.0.1
container_name: app2
restart: on-failure
environment:
- START_WITH_MESSAGE=false # Wait for a message before responding
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-2
networks:
app-network-1:
driver: overlay
attachable: true
app-network-2:
driver: overlay
attachable: true
```
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
### How to Set Up and Run the Overlay Network Example
1. **Create Virtual Machines (VMs):** Set up three VMs (VM1, VM2, VM3).
2. **Install Docker on Each VM:**
```bash
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
```
If you run into permission issues, use:
```bash
sudo groupadd docker
sudo usermod -aG docker $USER
newgrp docker
```
3. **Initialize Docker Swarm on VM1:**
```bash
docker swarm init
```
- Copy the command it gives (starting with `docker swarm join ...`) and run it on **VM2** and **VM3** to add them to the swarm.
4. **Copy the `docker-compose.yaml` to VM1:**
```bash
scp -i .ssh/<KEY_NAME> docker-compose.yaml <USER>@<VM1_IP>:/home/<USER>
```
5. **Deploy the Stack on VM1:**
```bash
docker stack deploy -c docker-compose.yaml mystack
```
6. **Check the Status and Logs:**
```bash
docker stack services mystack
docker stack logs app1
```
And that's it! You've now deployed an application using Docker Swarm and overlay networks. In this setup, `app1` and `app2` can communicate across different VMs.
### Summary
- **Bridge Networks** are great for communication on a single Docker host.
- **Overlay Networks** enable container communication across multiple hosts in a Docker Swarm.
By following this tutorial, you should now have a basic understanding of how to use bridge and overlay networks in Docker!
\ No newline at end of file
# Use the official Python image from the Docker Hub
FROM python:3.9-slim
# Set environment variables to reduce Python's buffer for more efficient logging
ENV PYTHONUNBUFFERED=1
# Create a directory for the app
WORKDIR /app
# Copy the current directory (where your script is) to /app in the container
COPY . /app
# Install requirements - NOTE: --no-cache-dir prevents pip from storing downloaded files in local cache (reduces image size).
RUN pip install --no-cache-dir -r requirements.txt
# Set the default command to run the Python script
CMD ["python", "main.py"]
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3-management
container_name: rabbitmq
ports:
- "5672:5672" # RabbitMQ default messaging port
- "15672:15672" # RabbitMQ management console
networks:
- app-network-1
- app-network-2
app1:
image: franciscomendonca/auto-messaging:1.0.1
restart: on-failure
environment:
- START_WITH_MESSAGE=true # Start by sending a message
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-1
app2:
image: franciscomendonca/auto-messaging:1.0.1
container_name: app2
restart: on-failure
environment:
- START_WITH_MESSAGE=false # Wait for a message before responding
- RABBITMQ_HOST=rabbitmq
depends_on:
- rabbitmq
networks:
- app-network-2
networks:
app-network-1:
driver: overlay
attachable: true
app-network-2:
driver: overlay
attachable: true
\ No newline at end of file
import pika
import time
import random
import os
import logging
import uuid
# Set up logging
logging.basicConfig(level=logging.INFO)
# Set up connection parameters
rabbitmq_host = os.getenv('RABBITMQ_HOST') # RabbitMQ container name
# Check if the RabbitMQ host is set
if not rabbitmq_host:
logging.error("RABBITMQ_HOST environment variable is not set")
exit(1)
logging.info(f"RabbitMQ host: {rabbitmq_host}")
connection_params = pika.ConnectionParameters(host=rabbitmq_host)
# Function to send messages
def send_message(channel, message):
# Send a message back to the queue
channel.basic_publish(exchange='',
routing_key='test_queue',
body=message)
print(f" [x] Sent '{message}'")
# Function to handle received messages and send a response
def on_message_received(ch, method, properties, body):
received_message = body.decode()
print(f" [x] Received '{received_message}'")
# Create a response message
response_message = f"Response to '{received_message}' from {random.randint(1, 1000)}"
# Simulate some processing time
time.sleep(2)
# Send the response message
send_message(ch, response_message)
# Function to start the auto-messaging system
def start_auto_messaging(start_with_message):
# Set up a connection and channel
logging.info(f"Establishing connection: {connection_params}")
connection = pika.BlockingConnection(connection_params)
channel = connection.channel()
logging.info("Connection established")
# Declare a queue
channel.queue_declare(queue='test_queue')
# Check if the system should start by sending a message
if start_with_message:
logging.info("Starting with an initial message")
initial_message = f"Initial message from {random.randint(1, 1000)}"
send_message(channel, initial_message)
# Start consuming and handle each message with the on_message_received function
channel.basic_consume(queue='test_queue',
on_message_callback=on_message_received,
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
# Read environment variable to check if the system should start by sending a message
start_with_message = os.getenv('START_WITH_MESSAGE', 'false').lower() == 'true'
logging.info(f"Does it start messaging: {start_with_message}")
# Start the auto-messaging system
start_auto_messaging(start_with_message)
pika
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment