Subindo Aplicações Web em Produção | Aprendendo HEROKU

Subindo Aplicações Web em Produção | Aprendendo HEROKU

Introduction to Scalable Modern Projects

Overview of the Video Series

  • Fabio Akita introduces the first video of 2022, which is part one of a two-part series discussing the "12 factors" for creating scalable modern projects.
  • Emphasizes that familiarity with Heroku is essential for understanding the content; it serves as a foundational platform for deploying applications.

Addressing Previous Discussions

  • Akita reflects on feedback regarding his previous example involving ingresso.com and suggests using a virtual queue system to manage access to outdated cinema reservation systems.
  • He cites Caixa Econômica Federal's implementation of a virtual queue during the Mega Sena lottery draw, highlighting its necessity due to high traffic.

Challenges in System Implementation

Issues Faced by Large Systems

  • Discusses potential problems with high traffic levels overwhelming even robust systems like Amazon, suggesting that unexpected demand can lead to failures.
  • Acknowledges that while there are skilled programmers, bureaucratic obstacles often hinder effective system development within public sectors.

The Inefficiency of State Systems

  • Argues that state-created systems will never match private sector efficiency due to lack of competition and accountability.
  • Critiques monopolistic practices where companies collude with governments, leading to subpar services without incentive for improvement.

The Nature of Software Development

Continuous Improvement Required

  • Stresses that software should never be considered "finished"; it requires ongoing updates and improvements.
  • Highlights how legacy systems create inefficiencies and technical debt, resulting in poor user experiences over time.

Introduction to Heroku and 12-Factor Methodology

Importance of Understanding Heroku

  • Introduces Heroku as a pivotal platform in modern application deployment and mentions Adam Wiggins' 12-factor methodology as crucial knowledge for developers.

Historical Context of Deployment Practices

  • Contrasts current deployment methods with outdated practices from the late '90s, emphasizing how manual server configurations are no longer viable.

How to Deploy a PHP Application on Heroku

Getting Started with Heroku

  • The tutorial emphasizes the simplicity of deploying applications on Heroku, starting with the requirement of having an account created on the platform.
  • It is essential for developers to have a basic understanding of Git, as it is fundamental for modern project collaboration and deployment.
  • To use Heroku, one must install the Heroku Command Line Interface (CLI), which can be done easily depending on the operating system (e.g., using yay -S heroku-cli for Arch Linux or Snap for Ubuntu).

Cloning and Setting Up Your Project

  • After installing the CLI, users are instructed to clone a sample PHP Symfony project, assuming familiarity with Git commands like git clone.
  • Users can create multiple applications under their Heroku account; starting with free options is encouraged. The command heroku create registers a new application.

Pushing Code to Heroku

  • Once registered, users push their code by executing git push heroku main, which sends the main branch's code to the remote repository created by Heroku.
  • This process automatically installs necessary buildpacks for PHP applications, including tools like Composer and web servers such as Apache or NGINX.

Understanding Buildpacks and Containers

  • The concept of buildpacks in Heroku predates Docker; they serve a similar purpose but were developed earlier. Docker was inspired by methodologies established by platforms like Heroku.
  • When pushing code, it triggers processes akin to creating a Docker image. Applications run in isolated environments called dynos.

Scaling Your Application

  • Users can scale their application using heroku ps:scale web=1, allowing them to manage how many dynos are running concurrently.

Understanding Dynos and Load Balancing in Heroku

Theoretical Request Handling Capacity

  • A single dyno can theoretically handle up to 10 requests per second, allowing for a maximum of 40 requests with one dyno and 80 requests with two dynos. However, this is contingent on resource availability during request processing.

Containers vs. Virtual Machines

  • Containers like Docker are not virtual machines; they partition machine resources, enabling isolated program execution as if each were on its own machine. This allows efficient resource management and billing.

Scaling Applications with Dynos

  • Using the ps:scale command in Heroku allows deployment across multiple dynos, meaning several web servers can run simultaneously. Incoming user requests are managed by a load balancer that distributes them among available dynos.

Understanding Local Development vs. Containerized Environments

  • In local development, web servers listen on specific ports (e.g., localhost:3000). With multiple containers running their own servers, each has a unique internal IP address, necessitating different access methods.

Implementing Load Balancers

  • To manage multiple containers effectively, a third container can be set up as a load balancer (e.g., NGINX or HAProxy), which routes incoming traffic based on predefined rules to the appropriate backend containers.

Monitoring Application Logs in Heroku

Real-Time Log Monitoring

  • To monitor application logs in real-time on Heroku, use the command heroku logs --tail, similar to using tail log/application.log locally. This keeps the log open for continuous updates.

Importance of Procfile in Deployment

  • Every application deployed on Heroku must include a Procfile at the project root to define how the app runs within its container (e.g., specifying commands for web processes).

Types of Containers Beyond Web Applications

What are Other Foreman Clones Written in Go?

Scaling Applications on Heroku

  • Discusses the concept of clones of Foreman written in Go, emphasizing that the language used is irrelevant as it reads from the Procfile to execute commands.
  • Explains how to scale applications by using the command heroku ps:scale and adjusting the number of web containers (e.g., web=2).
  • Highlights that scaling isn't a simple task; increasing dynos requires sufficient underlying resources like database connections, CPU, and RAM.
  • Suggests creating scripts to manage dyno counts based on traffic patterns to optimize costs effectively.

Managing Dependencies Across Programming Languages

  • Introduces Bundler for Rails developers to manage dependencies through a Gemfile, stressing that manual library downloads are unacceptable.
  • Outlines dependency management in JavaScript with npm or yarn, which updates package.json automatically upon installation.
  • Mentions tools like Maven and Gradle for Java, and pip for Python, emphasizing standardized dependency declaration files (build.gradle, requirements.txt).

Importance of Dependency Lock Files

  • Discusses how lock files (e.g., package-lock.json) ensure consistent library versions across different environments and among developers.
  • Warns against version discrepancies causing bugs when libraries are not managed properly; emphasizes precise version control as crucial for stability.

PHP Dependency Management with Composer

  • Describes how PHP projects utilize Composer with files like composer.json and composer.lock for managing dependencies efficiently.
  • Explains that running composer update locally ensures all dependencies are downloaded correctly before pushing changes to Heroku.

Adding New Functionality in Development

  • Illustrates adding new features by using Composer's command to require new libraries (e.g., adding cowsayphp) while ensuring proper installation via updates.

How to Deploy Changes to Heroku

Adding Modifications to Git Repository

  • To add changes made in the project, use git add .. Be cautious not to include unnecessary files.
  • The project includes a .gitignore file, ensuring only relevant files (like Composer and modified index.php) are added.
  • Always run git status before committing changes to verify what will be included.
  • Finalize changes with git commit -m "descriptive message" for clarity on modifications.

Pushing Changes to Heroku

  • Execute git push heroku main to upload modifications and generate a new image on Heroku.
  • Heroku automatically runs composer update, downloads libraries, regenerates images, and manages dynos during deployment.
  • Use the command heroku open cowsay for quick access to the application URL; this is faster than manual entry.

Continuous Deployment Process

  • The process described exemplifies continuous deployment, allowing seamless updates of applications on Heroku.

Utilizing Add-ons: Papertrail

  • The next tutorial step involves installing an add-on called Papertrail for log management and monitoring via a web interface.
  • Install it using the command heroku addons:create papertrail, which may have various options including paid plans.
  • Check installed add-ons with heroku addons, confirming Papertrail's installation.

Accessing Logs with Papertrail

  • Open the Papertrail web interface using heroku addons:open papertrail, enabling log searches across multiple active dynos.

Advanced Command Line Usage

  • For experienced developers, Heroku allows opening a new container with secure SSH connection for debugging or running commands like PHP shell or Rails console.

Understanding Environment Variables

  • Environment variables are crucial; they can be declared globally in local sessions (e.g., using .profile or .bashrc).

Best Practices for Environment Variables

  • It's good practice to declare configurations as environment variables within containers. A .env file simulates these variables locally without cluttering Bash profiles.

Managing Sensitive Information

  • Maintain a .env.example file for reference when cloning projects but ensure that actual .env files are listed in .gitignore.

Production Configuration on Heroku

Managing Environment Variables in Heroku

Setting and Accessing Environment Variables

  • To read environment variables in PHP, use the getenv function. For setting a variable like TIMES, use the command heroku config:set TIMES=20.
  • Environment variables are secure as they exist only within the container. If someone accesses your token, it indicates a larger security issue with access to your production container.
  • Never include sensitive information such as tokens or passwords in Git repositories; this is crucial for maintaining security.

Deploying Changes to Heroku

  • After making changes, run git add ., commit with a message using git commit -m, and push to Heroku with git push heroku main. This creates a new image reflecting your modifications.
  • The last step of the tutorial involves adding Postgres as an addon. Choose an appropriate size for your database to avoid complications during upgrades.

Connecting PHP Application to Postgres Database

Adding PDO Library

  • Use Composer to add the PDO library (csanquer/pdo-service-provider) for database interactions, similar to DAO patterns in Java or .NET.
  • Run composer update after requiring the library to ensure all dependencies are correctly installed.

Configuring Database Access

  • The database URL is stored in an environment variable called DATABASE_URL. Use heroku config to view it.
  • Utilize the getenv function to parse components from the connection string and configure PDO settings like username, password, host, port, and path.

Creating Routes and Templates

Implementing Database Queries

  • Create a new route /db that uses PDO for querying the database. Loop through results using a while statement to build an array of names returned from the query.

Using Twig for HTML Rendering

  • Symfony's Twig template engine will be used for rendering HTML. Create a file named views/database.twig that generates an HTML list from names passed into it.

Handling Database Migrations

Importance of Migrations

  • Modern web frameworks utilize migrations for creating tables and pre-populating data (e.g., admin accounts). Learn about migrations specific to your framework as they are essential for managing database schema changes effectively.

Directly Interacting with PostgreSQL Console

  • Open PostgreSQL console on Heroku using heroku pg:psql. Execute commands directly on your new database instance.

Introduction to Heroku and Database Interaction

Opening the Browser and Query Execution

  • The command heroku open db is used to access the newly created route, allowing users to execute queries on the database.
  • Successfully retrieves two rows that were just inserted into the database and generates HTML from them.

Basic Understanding of Heroku

  • This section covers fundamental concepts about Heroku, emphasizing its capabilities beyond basic operations.
  • At the end of the tutorial, links are provided for further reading, such as "How Heroku Works," which delves deeper into application lifecycle management in dynos.

Understanding Releases in Heroku

Release Management

  • Each time a new version is pushed using git push heroku, a new image is created with recent modifications while old images remain accessible.
  • The command heroku releases lists all deployments since inception, with each release being numbered for easy reference.

Rollback Feature

  • If a newly deployed version causes issues, users can quickly revert to a previous stable release using commands like heroku releases:rollback v10.
  • This rollback capability allows for efficient troubleshooting compared to manual updates via FTP.

Longevity and Relevance of Heroku

Timelessness of Tools

  • Despite rapid changes in technology, tools like Git and Heroku have remained relevant over a decade due to their consistent functionality.
Video description

Finalmente vou mostrar o que é o Heroku e como é o fluxo de trabalho mínimo de um projeto web ideal. Se você já usa Heroku, aproveite pra compartilhar o video com conhecidos que ainda não usam. Se nunca viu Heroku, prepare-se pra ficar surpreso! ## Conteúdo 00:00 - Intro 00:41 - Mega Sena da Virada 02:33 - Concorrência 04:11 - Intro a Heroku 04:46 - Deploy antigo 06:24 - Iniciando Tutorial Heroku 06:49 - Setup: Git é Básico! 07:22 - Heroku Login 08:18 - Primeiro Deploy 10:03 - Buildpack? Dockerfile? 10:35 - Entendendo Dynos e Containers 11:30 - Escalando Dynos 13:16 - Entendendo Load Balancer 16:41 - Vendo logs dos Dynos 17:22 - Entendendo Procfiles 18:58 - Mais sobre escalar dynos 20:21 - Entendendo Gerenciamento de Dependências 24:37 - Adicionando nova dependência 26:40 - Adicionando Addons 28:16 - Conectando num shell remoto 29:41 - Configurando com variáveis de ambiente 33:39 - Adicionando Banco de Dados 37:13 - Database Migrations 37:47 - Conectando no Banco de Dados 39:22 - Releases e Rollback 40:34 - Conclusão ## Links * Mega da Virada: Loterias Caixa colocam fila em app, e site fica fora do ar (https://tecnoblog.net/noticias/2021/12/31/mega-da-virada-loterias-caixa-colocam-fila-em-app-e-site-fica-fora-do-ar/) * Getting Started on Heroku with PHP (https://devcenter.heroku.com/articles/getting-started-with-php#set-up) * Transcript: https://www.akitaonrails.com/2022/01/10/akitando-112-subindo-aplicacoes-web-em-producao-aprendendo-heroku * Podcast: https://anchor.fm/dashboard/episode/e1cln4e