13 Deploying Data Science Projects
13.1 Understanding Deployment for Data Science
Deployment is getting the work somewhere other people can reach it. What that means depends on what you built: publishing an analysis report, putting a Shiny or Dash dashboard on a URL, or exposing a model at an endpoint another program can call. The platforms differ, and so does the amount of ceremony each one needs.
13.1.1 Why Deployment Matters
Deployment gets little attention in data science training, yet it decides whether anyone besides you can use the result. It also tests your environment file: a project won’t deploy until everything it depends on is written down, so a failed deploy is often the first sign that the file was incomplete.
13.1.2 Static vs. Dynamic Deployment
The first question about any project is whether it needs a server running when someone visits.
Static content is generated ahead of time and served as files — a rendered Quarto report, a documentation site, a chart that doesn’t respond to input. Nothing executes when a reader opens it. That makes static hosting cheap or free, fast, and close to impossible to attack, since there’s no code running for an attacker to reach.
Dynamic applications run code per request: a Shiny or Dash dashboard that filters on a dropdown, a model API that returns a prediction, anything that shows a user their own data. You need this when the output depends on the input, and it costs you a running process, a bill that scales with traffic, and a surface someone could attack.
Reach for static whenever the answer is the same for every reader.
13.1.3 Deployment Requirements by Project Type
Different data science projects have specific deployment requirements:
| Project Type | Interactivity | Computation | Data Access | Suitable Platforms |
|---|---|---|---|---|
| Analysis reports | None | None | None | GitHub Pages, Netlify, Vercel, Posit Connect Cloud |
| Interactive visualisations | Medium | Low | Static | GitHub Pages (with JavaScript), Netlify |
| Dashboards | High | Medium | Often dynamic | Render, Fly.io, Railway, Posit Connect Cloud |
| ML model APIs | Low | High | May need database | Google Cloud Run, Azure Container Apps |
Match the row to your project, then choose from the last column.
13.2 Deployment Platforms for Data Science
The options below are ordered roughly by how much you need to know to use them.
Each entry says what a platform charges for rather than what it charges. Prices and free-tier allowances move too fast to print — Netlify and AWS both restructured theirs during 2025, and Heroku withdrew its free tier altogether — so each entry links to the provider’s own pricing page instead. What a platform bills you for changes far less often, and it’s the part that decides whether it suits your project: a service billed per always-on process is a poor fit for something used twice a week, whatever the number attached to it.
13.2.1 Static Site Deployment Options
13.2.1.1 GitHub Pages
GitHub Pages offers free hosting for static content directly from your GitHub repository:
Best for: HTML reports, documentation, simple visualisations Setup complexity: Low Cost: Free for public repositories Limitations: Only static content, and GitHub applies a size limit to the published site — see GitHub’s own page for the current figure
Quick setup:
# Assuming you have a GitHub repository
# 1. Create a gh-pages branch
git checkout -b gh-pages
# 2. Add your static HTML files
git add .
git commit -m "Add website files"
# 3. Push to GitHub
git push origin gh-pages
# Your site will be available at: https://username.github.io/repositoryPushing the rendered output by hand gets old quickly. The alternative is to let GitHub render it for you on every push, using GitHub Actions: you commit your source .qmd files, and a workflow file at .github/workflows/publish.yml describes the machine that should build them.
This is continuous integration — having a server rebuild and re-test your project automatically whenever you push. This chapter uses it as a deployment mechanism and shows complete workflow files; Optimising Workflows comes back to the idea properly and explains what else it buys you. For now, read the YAML as a recipe: a description of a fresh machine, what to install on it, and what to run. We work through a complete Quarto workflow later in this chapter, under Deploying a Data Science Report to GitHub Pages.
Workflow steps reference reusable actions by major version, as in uses: actions/checkout@v7. Those majors are republished periodically, usually because GitHub has moved the runner to a newer Node.js version, and old majors eventually stop working. The versions in this book were current when it was written. Check github.com/actions and pin to whatever the current major is when you set your workflow up.
13.2.1.2 Netlify
Netlify provides more advanced features for static sites:
Best for: Static sites that require a build process Setup complexity: Low to medium Cost: Free tier, then paid plans — current pricing Limitations: Deploys, bandwidth and compute all draw from one credit allowance, so a burst of traffic and a burst of rebuilds compete with each other
In September 2025 Netlify replaced its separate bandwidth and build-minute allowances with a single credit balance. Deploys, bandwidth, compute and requests now all draw from the same pool at published rates, which means a busy month of traffic eats into the same budget as a busy month of rebuilds.
Tutorials written before that change describe two separate allowances, one in gigabytes and one in build minutes. Those terms still apply to accounts created before the cutover, which is why you’ll see both stories in circulation. Any account you open now gets credits.
Quick setup:
Netlify’s servers can’t execute the R or Python code in a Quarto document, so the site has to be rendered somewhere that can. The simplest route renders on your own machine and uploads the result:
# From the project directory. The first run asks you to authenticate with Netlify
quarto publish netlifyTo have Netlify rebuild on every push instead, connect the repository and add Quarto’s Netlify build plugin. The plugin renders Markdown only, so pages with code need their results committed through Quarto’s freeze option. Quarto’s Netlify guide has the two configuration files the plugin needs.
13.2.1.3 Vercel
Vercel, from the makers of Next.js, hosts static sites and serverless functions. For our purposes its distinguishing feature is that it runs a Python web app as functions, so a mostly-static site can still call a small piece of server-side code without you running a server.
Best for: Static sites with interactive elements, data visualisations with JavaScript, projects using modern web frameworks Setup complexity: Low to medium Cost: Free Hobby plan for personal, non-commercial projects; paid plans billed per developer seat — current pricing Limitations: Optimised for frontend applications; serverless functions have execution time limits, so this is not where long-running model training belongs
Quick setup:
Vercel’s build image has neither Quarto nor R, so render the report yourself, on your machine or in CI, and deploy the rendered folder:
# Install the Vercel CLI (needs Node.js)
npm install -g vercel
# Render, then deploy the output folder. The first run asks you to log in
quarto render
vercel deploy _site --prod_site is where a Quarto website writes its output; use your project’s output-dir instead if it sets one.
Example use case: a report with Observable Plot or D3.js charts can fetch fresh data from a small Flask or FastAPI app deployed to Vercel as its own project. Vercel looks for an app object in a file such as app.py or main.py, installs the packages listed in requirements.txt or pyproject.toml, and runs the app with no server for you to maintain. Its Python runtime guide covers the setup.
13.2.1.4 Quarto Pub
Quarto Pub, Quarto’s own free host for public documents, is being replaced by Posit Connect Cloud. It has stopped taking new accounts and stops accepting new documents and updates on 31 December 2026; existing pages stay at their current addresses until the end of 2031 (Posit’s announcement). For a new project, publish to Connect Cloud from the project directory:
quarto publish posit-connect-cloudConnect Cloud is covered with the dynamic platforms below.
13.2.2 Dynamic Application Deployment
Heroku used to be the default recommendation for deploying small Python and R web apps, and many older tutorials still mention its free tier. Heroku discontinued its free product tiers in November 2022 and now charges for all dynos — its name for the container your application runs in. It’s still a perfectly good platform. If you want a free plan to start on, Render and Posit Connect Cloud both have one. Fly.io and Railway offer a trial credit and then bill by usage, and Cloud Run’s monthly free allowance still needs a billing account on file.
13.2.2.1 Render
Render is the most direct successor to old-Heroku for data science workloads:
Best for: Python and R web applications, Dockerised dashboards Setup complexity: Medium Cost: Free tier for experimentation; paid plans billed per always-on service — current pricing Limitations: Free-tier services sleep when idle, so the first request after a quiet period waits for the service to wake
Setup for a Python web application:
- Create a
requirements.txtfile:
flask==3.1.3
pandas==3.0.5
matplotlib==3.11.1
gunicorn==26.0.0
Every pinned version here was current when this was written and will be out of date by the time you read it — that’s the nature of printing version numbers. Pinning is still the right practice; the specific numbers are illustrative.
The reliable way to produce this file is to generate it from an environment you’ve actually tested, rather than copying versions out of a book:
uv pip freeze > requirements.txtSee Reproducible Environments. Check PyPI, or run pip index versions <package>, when you want to know what’s current.
- Push your project to a GitHub repository
- Sign up at render.com
- Connect your GitHub repository
- Create a new Web Service and configure it:
- Environment: Python
- Build Command:
pip install -r requirements.txt - Start Command:
gunicorn app:app
- Add any required environment variables (API keys, database URLs) in the Environment tab. Never commit secrets to your repo.
Render builds and deploys your app on every push to the configured branch, so there’s no separate git push render main step.
gunicorn app:app and its variants start the Python examples from here on.
Gunicorn is a production web server for Python. Flask and Dash come with a development server that prints a warning against using it in production, and Flask’s documentation says it “is not designed to be particularly secure, stable, or efficient”. Gunicorn runs your app across several worker processes and is built to face real traffic. You start the app with gunicorn instead of python app.py, with no change to the code. Streamlit works differently: it runs on its own server, started with streamlit run, in production as well as on your laptop.
app:app is module:variable. The part before the colon is the Python file to import (app.py, without the .py); the part after is the name of the object inside that file which gunicorn should serve. For a Flask app created with app = Flask(__name__) in app.py, both halves happen to be app — which is why the notation looks redundant until you meet a Dash app, where the servable object is server, and the command becomes gunicorn app:server.
13.2.2.2 Fly.io and Railway
Two other platforms worth knowing for small to mid-sized Python/R deployments:
- Fly.io: Deploys Docker containers globally on a pay-as-you-go basis. Good fit once you’re comfortable with Docker (covered in the previous chapter); the
flyctlcommand-line tool handles the build, push, and deploy steps with one command. - Railway: Similar developer experience to Render, with a trial credit to try it out before committing (current pricing). Good Postgres and cron support out of the box.
All three platforms use essentially the same mental model: connect a Git repo, describe how to build the app (either requirements.txt + a start command or a Dockerfile), and let the platform handle HTTPS, logging, and redeploys on push.
13.2.2.3 Posit Connect Cloud (and the shinyapps.io migration)
For R Shiny, Quarto, Streamlit, and Dash content, Posit’s hosted platform is the path of least resistance.
If you have read about deploying Shiny apps anywhere else, you have read about shinyapps.io. Posit is moving its users to Posit Connect Cloud. A migration tool in Connect Cloud, in preview, moves apps one at a time and lets you test each copy before you finalise it, and finalising redirects the old shinyapps.io address so links already shared keep working. Accounts that haven’t moved are migrated automatically in waves through 2027; Posit’s migration guide lists the dates by plan.
The practical advice depends on where you are:
- Starting fresh? Go straight to Connect Cloud. Don’t learn a workflow that’s being retired.
- Already on shinyapps.io? Use the migration tool at a time you choose. The automatic move finalises without giving you a chance to test.
Everything below targets Connect Cloud. The rsconnect package still handles both, and the deploy call is nearly identical, so the skill transfers either way.
Best for: R Shiny apps, Quarto documents, Streamlit and Dash applications Setup complexity: Low Cost: Free tier available; interactive applications count against plan limits differently from static documents, so check current pricing if you plan to host several Limitations: Tied to Posit’s platform — for full control over the runtime, use a container on Render or Cloud Run instead
Deployment from Git (the recommended path):
Connect Cloud publishes directly from a GitHub repository. Push your app, link the repo in the Connect Cloud interface, and it redeploys on every push — the same model as Render and Netlify. There are no tokens to manage in code, which makes it both the easiest and the safest route.
Deployment from the IDE:
The Publish button in RStudio (the blue arrow next to Run in the editor for app.R) walks you through linking an account and deploys in one click.
Deployment from the console:
If you script your deploys, install rsconnect and keep credentials out of the source file. Connect Cloud support arrived in rsconnect 1.6.0, so update an older copy first. Read credentials from environment variables set in your OS or in a .Renviron that’s listed in .gitignore:
install.packages("rsconnect")
# One-time setup. Opens a browser and links your Connect Cloud account.
rsconnect::connectCloudUser()
# Deploy your app
rsconnect::deployApp(
appDir = "path/to/your/app",
appName = "my-shiny-app",
account = "your-account-name"
)For a script that runs unattended — in CI, say — there is no browser to open. Create a service account in Connect Cloud, then authenticate with its OAuth client credentials, read from the environment rather than written into the file. This call needs rsconnect 1.10.0 or later:
rsconnect::connectCloudClientCredentials(
clientId = Sys.getenv("CONNECT_CLOUD_CLIENT_ID"),
clientSecret = Sys.getenv("CONNECT_CLOUD_CLIENT_SECRET"),
accountName = "your-account-name"
)setAccountInfo() is the shinyapps.io call, not the Connect Cloud one
Most tutorials you will find configure rsconnect with setAccountInfo(name, token, secret). That is the shinyapps.io function, and it was the only one that mattered for a decade. Connect Cloud uses the connectCloud* functions above; connectApiUser() is a third thing again, for self-hosted Posit Connect servers. Three products, three registration calls, and the error you get from picking the wrong one does not tell you which one you wanted.
Quarto has native support: quarto publish from the project directory offers Connect Cloud as a target and handles the rest. Useful for reports and dashboards that don’t need a Shiny server.
For apps whose computation is light enough to run in the browser, Shinylive compiles an R or Python Shiny app to WebAssembly, a format modern browsers can execute directly. The result is static files you can host on anything that serves files, such as GitHub Pages, Netlify or an S3 bucket, with no server to pay for or to wake up. The first visit is slower instead, while the browser downloads the WebAssembly runtime and the app’s packages; later visits reuse its cache.
Everything runs on the user’s machine, so the data ships to the browser and heavy computation will be slow. For a teaching demo, a small interactive figure, or a calculator over a modest dataset, it removes the server from the deployment problem.
13.2.3 Cloud Platform Deployment
For more complex or production-level deployments, cloud platforms offer greater flexibility and scalability:
13.2.3.1 Google Cloud Run
Cloud Run is ideal for containerised applications:
Best for: Containerised applications that need to scale Setup complexity: Medium to high Cost: Pay-per-use — you’re billed for the time your container spends handling requests, with a monthly free allowance on top (current pricing) Limitations: Requires Docker knowledge
Before you can deploy: Cloud Run is driven by the Google Cloud CLI, which is a separate install. This is a one-off, and every gcloud command in this chapter assumes it:
Install the Google Cloud CLI for your platform — there’s a Windows installer, and a
brew install --cask gcloud-clifor macOSAuthenticate. This opens a browser and links the CLI to your Google account:
gcloud auth loginCreate or select a project, and set it as the default so you don’t have to name it every time. Projects are how Google Cloud groups resources and bills them. A project ID has to be unique across all of Google Cloud, so choose your own: 6 to 30 lowercase letters, digits and hyphens, starting with a letter:
gcloud projects create your-project-id # or skip, if you have one gcloud config set project your-project-idLink a billing account to the project, then enable the two services this uses. Cloud Run has a monthly free allowance, but Google still requires a billing account on file before it will run anything:
gcloud billing accounts list # note the ACCOUNT_ID of the account to use gcloud billing projects link your-project-id --billing-account=ACCOUNT_ID gcloud services enable run.googleapis.com cloudbuild.googleapis.com
Confirm the CLI is working and pointed at the right project with gcloud config list.
The AWS equivalent is aws configure after installing the AWS CLI; Azure’s is az login. All three follow the same shape — install a command-line tool, authenticate it against your account in a browser, then set a default project or region.
Deployment steps:
From a directory containing a Dockerfile, one command does everything — Google builds the image for you, stores it, and deploys it:
gcloud run deploy app-name \
--source . \
--region us-central1 \
--allow-unauthenticatedgcr.io
You will find a great many Cloud Run guides that begin docker build -t gcr.io/your-project/app-name . followed by docker push. Don’t follow them. That is Google Container Registry, which was retired in 2025 — it stopped accepting pushes in March of that year and stopped serving reads in June. Its replacement is Artifact Registry, whose image paths look like us-central1-docker.pkg.dev/your-project/your-repo/app-name.
The --source . flag above sidesteps the question entirely: Cloud Build produces the image and files it in Artifact Registry without you naming a registry at all. Push images yourself only when you need the image to exist before the deploy — for example when the same image is deployed to several services.
13.2.3.2 AWS
AWS App Runner, the service that used to fill this slot on AWS, closed to new customers on 30 April 2026. Existing services keep running, and AWS recommends Amazon ECS Express Mode to anyone starting now. Reach for it when your organisation is already on AWS; otherwise Cloud Run and Render both reach a running container with less setup.
13.3 Step-by-Step Deployment Guides
Let’s walk through complete deployment workflows for common data science scenarios.
The examples below reference placeholder files like sales_data.csv and model.pkl, which stand in for your own data or trained model rather than being shipped with the book. (data/my_data.csv is the exception — that one is in the book’s repository, and the reporting examples use it.) When you follow along, either point the code at one of your own files, substitute a built-in dataset (e.g. ggplot2::diamonds for R, sns.load_dataset("tips") for Python), or pull a stable public CSV from a URL as shown in the Reporting and Visualisation chapters. The deployment mechanics don’t depend on which file you use.
13.3.1 Deploying a Data Science Report to GitHub Pages
This example shows how to publish an analysis report created with Quarto:
- Create your Quarto document,
report.qmd, in a project folder with the book’smy_data.csvin adatasubfolder:
---
title: "Sales Analysis Report"
author: "Your Name"
format: html
---
```{r}
#| echo: false
#| warning: false
#| message: false
library(ggplot2)
library(dplyr)
library(here)
# Load the data and aggregate it once, so the prose and the chart
# below are both reading the same numbers
sales <- read.csv(here("data", "my_data.csv"))
totals <- sales |>
group_by(Product) |>
summarise(Sales = sum(Sales)) |>
arrange(desc(Sales))
```
## Executive Summary
`r totals$Product[1]` leads the range at
`r round(100 * totals$Sales[1] / sum(totals$Sales))`% of sales in the period.
```{r}
#| echo: false
ggplot(totals, aes(x = reorder(Product, -Sales), y = Sales, fill = Product)) +
geom_col() +
theme_minimal() +
labs(title = "Total sales by product", x = "Product")
```Two details are doing real work here. The headline figure in the summary is inline R — a backtick expression starting with r, evaluated at render time and replaced by its result — rather than a number typed into the sentence, so it cannot disagree with the chart underneath it when the data changes. And the chart plots totals, one row per product, so the bars and the headline read the same numbers. On the raw sales frame, geom_col() would still reach the right heights, because it stacks one segment per row by default. Change its position to "dodge" or "identity" and the bars show single days instead, side by side or overlapping, and the tallest reads as a total it isn’t.
Put the project in a GitHub repository: commit
report.qmdanddata/my_data.csv, and push tomain.Publish once from your own machine. The workflow below can’t create the
gh-pagesbranch it publishes to, so the first publish has to happen locally:
quarto publish gh-pages report.qmdQuarto asks whether to publish using gh-pages. Answer yes and it creates the branch, renders the report and pushes it, and GitHub serves the result at https://username.github.io/repository. The render also leaves report.html, report_files/ and .quarto/ beside the source; add them to .gitignore, since the workflow renders its own copy.
- Create a GitHub Actions workflow file at
.github/workflows/publish.yml:
name: Publish Quarto Site
on:
push:
branches: [main]
jobs:
build-deploy:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Check out repository
uses: actions/checkout@v7
- name: Set up Quarto
uses: quarto-dev/quarto-actions/setup@v2
- name: Install R
uses: r-lib/actions/setup-r@v2
with:
r-version: 'release'
- name: Install R Dependencies
uses: r-lib/actions/setup-r-dependencies@v2
with:
# The `|` matters. Without it YAML folds the package names into
# a single space-joined string and the action fails to parse them.
packages: |
any::knitr
any::rmarkdown
any::ggplot2
any::dplyr
any::here
- name: Render and Publish
uses: quarto-dev/quarto-actions/publish@v2
with:
target: gh-pages
# report.qmd is a single document. The default path (.) only
# works for website, book or manuscript projects.
path: report.qmd
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}- Commit and push the workflow:
git add .gitignore .github/workflows/publish.yml
git commit -m "Publish the report on every push"
git push origin mainFrom then on, each push to main renders the report again and republishes it.
13.3.2 Deploying a Dash Dashboard to Render
This example demonstrates deploying an interactive Python dashboard:
- Create your Dash application (
app.py):
import dash
import pandas as pd
import plotly.express as px
from dash import Input, Output, dcc, html
# Load data
df = pd.read_csv('sales_data.csv')
# Initialize app
app = dash.Dash(__name__, title="Sales Dashboard")
server = app.server # For Render deployment
# Create layout
app.layout = html.Div([
html.H1("Sales Performance Dashboard"),
html.Div([
html.Label("Select Year:"),
dcc.Dropdown(
id='year-filter',
options=[{'label': str(year), 'value': year}
for year in sorted(df['year'].unique())],
value=df['year'].max(),
clearable=False
)
], style={'width': '30%', 'margin': '20px'}),
dcc.Graph(id='sales-graph')
])
# Create callback
@app.callback(
Output('sales-graph', 'figure'),
Input('year-filter', 'value')
)
def update_graph(selected_year):
filtered_df = df[df['year'] == selected_year]
fig = px.bar(
filtered_df,
x='quarter',
y='sales',
color='product',
barmode='group',
title=f'Quarterly Sales by Product ({selected_year})'
)
return fig
if __name__ == '__main__':
# debug=True must NEVER be used in production. It exposes
# an interactive Python console to anyone who can reach the app.
# Render runs `gunicorn` directly in production, so this block
# is only used when you run `python app.py` locally.
app.run(debug=False)- Create a
requirements.txtfile:
dash==4.4.1
pandas==3.0.5
plotly==6.9.0
gunicorn==26.0.0
- Create a minimal
Dockerfile:
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Run as an unprivileged user
RUN useradd --create-home appuser
COPY --chown=appuser:appuser . .
USER appuser
# sh -c fills in $PORT; exec then makes gunicorn the main process,
# so it receives the platform's stop signal
CMD ["sh", "-c", "exec gunicorn app:server -b 0.0.0.0:$PORT"]$PORT comes from
Render, Cloud Run, Fly.io and Heroku all set a PORT environment variable inside your container and expect the app to listen on it. You don’t choose the number and you shouldn’t hardcode one — the platform picks it and routes traffic there.
The catch is local testing. Run this image on your own machine and $PORT is empty, so gunicorn tries to bind to 0.0.0.0: and fails with an unhelpful error. Supply one yourself:
docker run -e PORT=8080 -p 8080:8080 my-dashboardSign up for Render and connect your GitHub repository
Create a new Web Service on Render with these settings:
- Name: your-dashboard-name
- Environment: Docker
- Build Command: (leave empty when using Dockerfile)
- Start Command: (leave empty when using Dockerfile)
Deploy your application
Your interactive dashboard will be available at the URL provided by Render.
13.3.3 Deploying a Shiny Application to Posit Connect Cloud
This example shows how to deploy an R Shiny dashboard:
- Create a Shiny app directory with
app.R, and copy the book’smy_data.csvinto adatafolder inside it, so everything the app needs travels with it:
sales-dashboard/
├── app.R
└── data/
└── my_data.csv
library(shiny)
library(ggplot2)
library(dplyr)
library(DT) # install.packages("DT") - interactive tables
# Load data. Shiny runs an app from its own folder, locally and once
# deployed, so a path relative to app.R works in both places
sales <- read.csv("data/my_data.csv")
# UI
ui <- fluidPage(
titlePanel("Sales Analysis Dashboard"),
sidebarLayout(
sidebarPanel(
# "All" first and selected, so the app opens on the whole dataset
selectInput("region", "Select Region:",
choices = c("All", sort(unique(sales$Region))),
selected = "All"),
# Every product ticked by default, for the same reason
checkboxGroupInput("products", "Select Products:",
choices = sort(unique(sales$Product)),
selected = sort(unique(sales$Product)))
),
mainPanel(
plotOutput("salesPlot"),
DT::DTOutput("salesTable")
)
)
)
# Server
server <- function(input, output) {
filtered_data <- reactive({
data <- sales |> filter(Product %in% input$products)
if (input$region != "All") {
data <- data |> filter(Region == input$region)
}
data
})
output$salesPlot <- renderPlot({
# Nothing sensible to draw if the user unticks every product
req(nrow(filtered_data()) > 0)
ggplot(filtered_data(), aes(x = Product, y = Sales, fill = Product)) +
geom_bar(stat = "summary", fun = sum) +
theme_minimal() +
labs(title = paste("Total sales —", input$region), y = "Sales")
})
output$salesTable <- DT::renderDT({
filtered_data() |>
group_by(Product) |>
summarise(Total = sum(Sales),
Average = mean(Sales))
})
}
# Run the application
shinyApp(ui = ui, server = server)Note DT::DTOutput() and DT::renderDT() rather than Shiny’s own dataTableOutput() and renderDataTable(). Shiny deprecated those years ago in favour of the DT package, and calling them now prints deprecation messages to your console that are hard to interpret if you don’t know what they refer to. Most tutorials still show the old names.
The app reads its data by a path relative to app.R instead of with here(). here() works from the project root, which it finds by looking for files such as .git or an .Rproj. On your machine that’s the repository; on the server, where those files aren’t uploaded, it’s the app folder, so the same here() call points at two different places.
Three choices in that app carry over to your own. Filter on a column with repeated values — Region here — because filtering on something close to a unique key leaves one row or none per choice. (The book’s sample file is small enough that East and West still come down to a single product each, so those two regions draw one bar.) Open on everything: "All" as the first choice and every product ticked, so the first thing a stakeholder sees is the full picture rather than a corner of it. And req() stops a render early when its condition is false, which is how you handle the user unticking everything: Shiny clears the plot instead of showing an error in the browser.
geom_bar(stat = "summary", fun = sum) totals the rows within each product before drawing, one bar per product. stat = "identity" draws the rows themselves. Stacked, which is the default, they reach the same height; switch the position to "dodge" or "identity" and you get single days, side by side or overlapping.
Push the app directory to a GitHub repository and link it in Connect Cloud, which redeploys on every push. If you’d rather deploy from the console, configure
rsconnectas shown in the Connect Cloud section above, reading your credentials from the environment rather than writing them into the scriptDeploy your application:
rsconnect::deployApp(
appDir = "sales-dashboard", # Directory containing app.R and data/
appName = "sales-dashboard", # Name for your deployed app
account = "your-account-name" # Your Posit account name
)- Share the provided URL with your stakeholders
The deployed app gets a public URL you can share. Apps already published to shinyapps.io keep their existing https://your-account-name.shinyapps.io/... address, which redirects to the Connect Cloud URL after migration.
13.3.4 Deploying a Machine Learning Model API
This example demonstrates deploying a machine learning model as an API:
- Create a Flask API for your model (
app.py):
import os
import pickle
from flask import Flask, jsonify, request
import pandas as pd
# Initialize Flask app
app = Flask(__name__)
# Load the pre-trained model
with open('model.pkl', 'rb') as file:
model = pickle.load(file)
@app.route('/predict', methods=['POST'])
def predict():
try:
# Get JSON data from request
data = request.get_json(force=True)
if not isinstance(data, dict):
return jsonify({
'status': 'error',
'message': 'Request body must be a JSON object of feature: value pairs',
}), 400
# Convert to DataFrame
input_data = pd.DataFrame(data, index=[0])
# Make prediction
prediction = model.predict(input_data)[0]
# Return prediction as JSON
return jsonify({
'status': 'success',
'prediction': float(prediction),
'input_data': data,
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e),
}), 400
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'healthy'})
if __name__ == '__main__':
# In production, gunicorn runs the app directly. This block is
# only used for local development.
app.run(host='0.0.0.0', port=int(os.environ.get('PORT', '8080')))For production use you would want stricter input validation (for example with Pydantic or Marshmallow) and authentication. The try/except above only catches shape errors, not adversarial input.
- Create a
requirements.txtfile:
flask==3.1.3
pandas==3.0.5
scikit-learn==1.9.0
gunicorn==26.0.0
- Create a
Dockerfile:
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN useradd --create-home appuser
COPY --chown=appuser:appuser . .
USER appuser
CMD ["sh", "-c", "exec gunicorn --bind 0.0.0.0:$PORT app:app"]- Deploy to Google Cloud Run:
# Build the container from the Dockerfile in this directory and deploy it.
# Cloud Build produces the image; Artifact Registry stores it. You don't
# have to name a registry.
gcloud run deploy model-api \
--source . \
--region us-central1 \
--allow-unauthenticated--allow-unauthenticated exposes the endpoint to the public internet
For a quick demo this is fine, but don’t leave a model API wide open to the internet without rate limiting and authentication. For production use, drop --allow-unauthenticated and require callers to present an identity token (gcloud auth print-identity-token), or put an API gateway — a service that sits in front of yours and handles authentication, rate limiting, and routing before requests reach it — in front of the service. At minimum, monitor the Cloud Run request count and set budget alerts so you notice unexpected traffic early.
- Test your API. Replace the host below with the URL
gcloud run deployprinted when it finished — it is unique to your service and thexxxx-xxhere is a stand-in:
# Bash, Git Bash, WSL, macOS
curl -X POST \
https://model-api-xxxx-xx.a.run.app/predict \
-H "Content-Type: application/json" \
-d '{"feature1": 0.5, "feature2": 0.8, "feature3": 1.2}'In Windows PowerShell, curl is an alias for Invoke-WebRequest, which doesn’t understand -X or -d. Calling the real curl.exe instead fails differently: Windows PowerShell 5.1 strips the double quotes out of the JSON before curl.exe receives it, and the API rejects what’s left. Use the native cmdlet, which sends the body as written, with a backtick rather than a backslash to continue each line:
Invoke-RestMethod -Method Post `
-Uri https://model-api-xxxx-xx.a.run.app/predict `
-ContentType "application/json" `
-Body '{"feature1": 0.5, "feature2": 0.8, "feature3": 1.2}'This API allows other applications to access your machine learning model’s predictions.
13.4 Deployment Best Practices
Regardless of the platform you choose, these best practices will help ensure successful deployments:
13.4.1 Environment Management
- Use environment files: Include
requirements.txtfor Python orrenv.lockfor R - Specify exact versions: Use
pandas==3.0.5rather thanpandas>=3.0 - Minimise dependencies: Include only what you need to reduce deployment size
- Test in a clean environment: Verify your environment files are complete
13.4.2 Security Considerations
- Never commit secrets: Keep API keys, database passwords, and access tokens in environment variables, platform-managed secret stores (Render Environment, Fly.io secrets, GCP Secret Manager, AWS Secrets Manager), or a local
.envfile that is listed in.gitignore. Data Stores covers the mechanics, including what to do if one leaks. - Set up proper authentication: Restrict access to sensitive applications. Don’t leave
--allow-unauthenticatedendpoints, default passwords, ordebug=Trueenabled in anything publicly reachable. - Implement input validation: Protect against malicious inputs, especially for any endpoint that touches a database or a machine learning model.
- Use HTTPS: Every modern platform-as-a-service (Render, Fly, Railway, Vercel, Cloud Run) issues the certificates that make HTTPS work automatically and at no cost; use them. Custom domains should always be served over HTTPS.
- Regularly update dependencies: Address security vulnerabilities. Tools like GitHub Dependabot or
pip-auditcross-check yourrequirements.txtagainst public databases of known flaws and tell you which of your packages need upgrading.
13.4.3 Observability: Logging, Health Checks, and Monitoring
Once your application is deployed, you need to know when it breaks:
Emit structured logs to stdout/stderr: Modern platforms capture anything your app prints and surface it in their dashboards. Use Python’s
loggingmodule (orlgr/futile.loggerin R) rather thanprint, and log in JSON where possible so the logs are searchable.Expose a
/healthendpoint: A simple route that returns HTTP 200 when the app is alive lets the platform (and uptime monitors like UptimeRobot or BetterStack) restart unhealthy instances automatically. The ML API example in this chapter already does this.Add a Docker
HEALTHCHECKin your Dockerfile so the container itself reports its status:HEALTHCHECK --interval=30s --timeout=10s --retries=3 \ CMD python -c "import os,urllib.request; \ urllib.request.urlopen(f'http://localhost:{os.environ.get(\"PORT\",8080)}/health')"The check calls Python because the slim images have no
curl; best practice 8 in Containerisation covers what else a healthcheck has to line up with.Track errors separately: Services like Sentry or Better Stack give you grouped stack traces and notifications when something goes wrong. Both have free tiers sized for small projects.
Set budget alerts: On pay-per-use platforms (Cloud Run, AWS, GCP) configure a monthly budget with email alerts before you deploy anything that autoscales.
13.4.4 Performance
Most slow dashboards are slow for the same reason: they reload and recompute the whole dataset on every interaction. Load the data once when the process starts, cache anything expensive that doesn’t depend on user input (@st.cache_data in Streamlit, shiny::bindCache() in Shiny, functools.lru_cache in plain Python), and push filtering and aggregation into the database rather than pulling everything and doing it in memory.
If a computation takes longer than a few seconds, it doesn’t belong in a request. Precompute it on a schedule and have the app read the result.
13.4.5 Documentation
A README that says how to run the thing locally, what environment variables it needs, and who to ask when it breaks. For an API, the endpoints and an example request. FastAPI generates that last part for you, which is a decent argument for it over Flask on anything you’ll hand to another team.
13.5 Troubleshooting Common Deployment Issues
13.5.1 Platform-Specific Issues
13.5.1.1 GitHub Pages
| Issue | Solution |
|---|---|
| Changes not showing up | Check if you’re pushing to the correct branch |
| Build failures | Review the GitHub Actions logs for errors |
| Custom domain not working | Verify DNS settings and CNAME file |
13.5.1.2 Render / Fly.io
| Issue | Solution |
|---|---|
| Application crash | Check the service’s Logs tab in the dashboard (flyctl logs on Fly.io) |
| Build failures | Ensure dependencies are pinned in requirements.txt and that the build command is correct |
| Free service sleeping when idle | Use periodic health-check pings, or upgrade to a paid tier that stays warm |
13.5.1.3 Posit Connect Cloud
| Issue | Solution |
|---|---|
| Package installation failures | Use renv to capture exact package versions in a lockfile |
| Application timeout | Optimise data loading and computation |
| Deployment failures | Check rsconnect logs in RStudio |
13.5.2 General Deployment Issues
- A missing package. The build or start-up log names it. Add it to
requirements.txtorrenv.lock, and rebuild the environment from that file on your own machine before redeploying. - A missing environment variable. Variables in your local
.envdon’t travel with the code; each one has to be set again in the platform’s settings, with the same name. In Python a missing one raisesKeyErroratos.environ[...], and in RSys.getenv()quietly returns an empty string. - A path that only exists on your laptop. Use paths relative to the project, written with forward slashes. Linux servers also treat
Data.csvanddata.csvas different files. - Files that disappear. Render’s filesystem is ephemeral and Cloud Run’s lives in memory, so anything the app writes is lost when it restarts or redeploys. Keep data the app needs to write in a database or object storage.
- Running out of memory. Free plans come with little memory, and an app that loads a whole dataset at start-up can be killed before it serves a request. Load only the rows and columns the app uses.
13.6 Conclusion
You’ll redeploy, read logs and fix what breaks for as long as a project is in use, which is why the platforms recommended here are the ones that make redeploying cheap.
By the end of this chapter you should have:
- A Quarto report that rebuilds and republishes to GitHub Pages on every push
- At least one dynamic application — Shiny, Dash, or Flask — running on a public URL
- Every credential in a platform secret store or a
.gitignored.Renviron/.env, and none in a file you’ve committed - A
requirements.txtorrenv.lockcomplete enough that the deployment built from a clean environment
If the second one is still failing, check three things first: a missing dependency in the environment file, an app bound to 127.0.0.1 instead of 0.0.0.0, and a hardcoded port where the platform expected $PORT.
The next chapter turns from getting one project deployed to making the whole cycle repeatable: project structure, automation, testing, and the continuous integration that catches a broken environment file before your users do.