aws ec2 start-instances \
--instance-ids i-0514a57a209efcf56 \
--profile dev-deployInstalling a Real Application
Logging into the instance
The install runs on the same AL2023 instance we set up in App Dependencies, which already has Python 3.12.1 in /opt. Every command in this section runs on our local machine.
Start the instance
If the instance was stopped, start it:
aws ec2 wait instance-running returns once the instance is up, so the next command doesn’t race it:
aws ec2 wait instance-running \
--instance-ids i-0514a57a209efcf56 \
--profile dev-deployLook up the public IP
A stopped instance gets a new public IP address every time it starts, so look it up again:
aws ec2 describe-instances \
--instance-ids i-0514a57a209efcf56 \
--query "Reservations[*].Instances[*].PublicIpAddress" \
--output text \
--profile dev-deployYOUR_PUBLIC_IP_ADDRESSConnect
Connect as ec2-user with the aws-dev key:
ssh -i ~/.ssh/aws-dev.pem -o IdentitiesOnly=yes -o IdentityAgent=none ec2-user@YOUR_PUBLIC_IP_ADDRESSThe two -o options stop ssh-agent from offering other keys first, which can end in Too many authentication failures. With an entry in ~/.ssh/config (see SSH config), the same connection is ssh aws-dev; update its HostName line with the new IP first.
The Amazon Linux 2023 banner and a [ec2-user@ip-...]$ prompt mean we’re on the instance. Two things can go wrong:
Connection timed out: our home IP changed, so the port 22 rule indev-sgno longer matches. The fix is in Logging into the instance.A fingerprint prompt:
known_hostsstores host keys by address, and the address is new. Typeyes(see Host key verification).REMOTE HOST IDENTIFICATION HAS CHANGED: AWS gave us an address thatknown_hostsalready has for a different server. Remove the old entry withssh-keygen -R YOUR_PUBLIC_IP_ADDRESSand connect again.
Installing into /opt
Third party software follows the same convention as the Python and R interpreters in App Dependencies. These are typically installed in their own directory tree under /opt, not scattered across the filesystem.
Here’s what that looks like for baseball-trajectory, a Shiny for Python app (source) that plots a player’s career arc from the MLB Stats API:
sudo git clone https://github.com/mjfrigaard/baseball-trajectory.git /opt/baseball-trajectoryCloning into '/opt/baseball-trajectory'...
remote: Enumerating objects: 161, done.
remote: Counting objects: 100% (161/161), done.
remote: Compressing objects: 100% (80/80), done.
remote: Total 161 (delta 77), reused 153 (delta 69), pack-reused 0 (from 0)
Receiving objects: 100% (161/161), 1.59 MiB | 36.89 MiB/s, done.
Resolving deltas: 100% (77/77), done.git is already installed on the instance (we set it up with the Python build in App Dependencies). The clone needs sudo because /opt is owned by root.
Then move into the new folder:
cd /opt/baseball-trajectoryCreating the virtual environment
Next, create a virtual environment from the /opt Python, not the system one (see Building Python from source). Then install the package and its dependencies into it:
sudo /opt/python/3.12.1/bin/python3.12 -m venv /opt/baseball-trajectory/.venvsudo /opt/baseball-trajectory/.venv/bin/pip install -e .pip builds the package, then resolves and downloads about 65 dependencies (shiny, polars, numpy, scipy, matplotlib, and everything they need). The output is long; it ends like this:
Building wheels for collected packages: baseball-trajectory
Building editable for baseball-trajectory (pyproject.toml) ... done
Created wheel for baseball-trajectory: filename=baseball_trajectory-0.1.0-py3-none-any.whl size=6333 sha256=...
Successfully built baseball-trajectory
Installing collected packages: zipp, wrapt, websockets, wcwidth, urllib3, ...
Successfully installed Babel-2.18.0 ... baseball-trajectory-0.1.0 ... shiny-1.9.0 ... statsmodels-0.15.0 ...
[notice] A new release of pip is available: 23.2.1 -> 26.3
[notice] To update, run: /opt/baseball-trajectory/.venv/bin/python3.12 -m pip install --upgrade pipSuccessfully installedlists every package, includingbaseball-trajectory-0.1.0itself.The
[notice]lines are informational: thevenvcopiedpip23.2.1 from the/optPython.
pip install pulls the app’s dependencies from PyPI, so the instance needs outbound internet access. If the instance is in a private subnet, verify the NAT gateway path works before you run this rather than after it hangs.
Where everything will live
The install spreads across four locations, and each one follows the convention from Where do language installations live? rather than throwing everything into one folder:
| Location | What lives there |
|---|---|
/opt/baseball-trajectory |
Application source and the virtual environment |
/etc/systemd/system/baseball-trajectory.service |
The unit file telling systemd how to run it |
journald |
Application stdout and stderr, read with journalctl -u baseball-trajectory |
/var/cache/baseball-trajectory |
Matplotlib’s font cache, created by systemd (see Fixing the Matplotlib cache warning) |
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace', "fontSize":"12px"}}}%%
graph TD
Root(["/"])
Opt("<strong>/opt/baseball-trajectory</strong>")
Venv("<strong>.venv/bin/shiny</strong><br/><strong>.venv/bin/baseball-trajectory</strong>")
Etc("<strong>/etc/systemd/system</strong>")
Unit("<strong>baseball-trajectory.service</strong>")
Log("<strong>journald</strong>")
Jctl("<em>journalctl -u baseball-trajectory</em>")
Root --"<em>application</em>"--> Opt --> Venv
Root --"<em>config</em>"--> Etc --> Unit
Root --"<em>logs</em>"--> Log --> Jctl
style Root fill:#d2562b,stroke:#fff,stroke-width:2px,color:#fff
style Opt fill:#e8a33d,stroke:#000,stroke-width:2px,color:#000,font-family:monospace
style Venv fill:#e8a33d,stroke:#000,stroke-width:1px,color:#000,font-family:monospace
style Etc fill:#2a6f77,stroke:#fff,stroke-width:2px,color:#fff,font-family:monospace
style Unit fill:#2a6f77,stroke:#fff,stroke-width:1px,color:#fff,font-family:monospace
style Log fill:#666,stroke:#999,stroke-width:2px,color:#fff,font-family:monospace
style Jctl fill:#666,stroke:#999,stroke-width:1px,color:#fff,font-family:monospace
Notice what’s missing: there’s no /var/lib entry. That’s because baseball-trajectory keeps no state on disk; the only thing it writes is a disposable Matplotlib cache. Rosters and career stats are fetched from https://statsapi.mlb.com and cached in memory, so a restart simply starts with an empty cache.
That also means outbound HTTPS isn’t only an install time requirement. The running app needs it for every new player lookup, so the network path out of the instance has to stay open (the diagram in the next section shows it).
Testing the app by hand
Before handing it to systemd, confirm the console script starts from the venv:
/opt/baseball-trajectory/.venv/bin/baseball-trajectoryThe app runs in the foreground and holds the terminal:
INFO: Started server process [206812]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)It binds to 127.0.0.1:8000, so it’s only reachable from the instance itself. Open a second terminal, connect with the same ssh command, and request the landing page headers:
curl -I http://127.0.0.1:8000HTTP/1.1 200 OK
date: Tue, 24 Nov 2026 04:59:23 GMT
server: uvicorn
content-length: 9743
content-type: text/html; charset=utf-8-I sends a HEAD request, which asks for the headers only. The first terminal logs the request as it arrives:
INFO: 127.0.0.1:41640 - "HEAD / HTTP/1.1" 200 OKStop the app with Ctrl+C in the first terminal before moving on. Left running, it holds port 8000 and the systemd service below fails with Address already in use.
^C
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [206812]Daemonizing with systemd
Next we’re going to turn baseball-trajectory into the kind of service described in Lab 10, running under the service account from Linux Users.
Started by hand from an SSH session, it dies the moment that session closes. When the app runs as a service, systemd starts it on boot, restarts it after a crash, and collects its output.
In front of the app, nginx terminates TLS (we’ll cover this in the Configure SSL chapter).
%%{init: {'theme': 'base', 'look': 'classic', 'themeVariables': {'fontFamily': 'monospace', "fontSize":"12px"}}}%%
graph TD
Op(["Operator<br/>browser"])
Admin(["You<br/>SSH client"])
subgraph EC2["EC2 Instance"]
Nginx("<strong>nginx</strong><br/>:443 TLS")
App("<strong>baseball-trajectory</strong><br/>127.0.0.1:8000")
Sysd("<strong>systemd</strong> + <strong>journald</strong>")
end
MLB["MLB Stats API<br/>statsapi.mlb.com"]
Op --"HTTPS :443"--> Nginx
Admin --"SSH :22"--> EC2
Nginx --"HTTP :8000"--> App
App --"<em>HTTPS :443</em>"--> MLB
Sysd --"<em>supervises</em>"--> App
style EC2 fill:#1B2A41,stroke:#fff,stroke-width:2px,color:#fff
style Op fill:#d2562b,stroke:#fff,stroke-width:2px,color:#fff
style Admin fill:#d2562b,stroke:#fff,stroke-width:2px,color:#fff
style Nginx fill:#2a6f77,stroke:#fff,stroke-width:1px,color:#fff
style App fill:#5b8c5a,stroke:#fff,stroke-width:2px,color:#fff
style MLB fill:#666,stroke:#999,stroke-width:1px,color:#fff
style Sysd fill:#e8a33d,stroke:#000,stroke-width:2px,color:#000
Notice the one outbound arrow: the security group and any NAT path have to allow outbound HTTPS to the MLB Stats API.
The service account
The unit file runs the app as baseball-trajectory, the service account from Creating a dedicated service account. Accounts live on the instance, so the AL2023 instance from Upgrade to Amazon Linux 2023 doesn’t have it yet. Check first:
id baseball-trajectoryid: ‘baseball-trajectory’: no such userCreate it with no login shell, in the system UID range:
sudo useradd -r -s /sbin/nologin baseball-trajectoryuseradd prints nothing when it succeeds, so run id again:
id baseball-trajectoryuid=993(baseball-trajectory) gid=993(baseball-trajectory) groups=993(baseball-trajectory)A UID below 1000 confirms -r put it in the system range.
The unit file
Create the unit file with vim (the steps for editing it are below):
sudo vim /etc/systemd/system/baseball-trajectory.serviceAnd give it this content:
[Unit]
Description=baseball-trajectory
After=network.target
[Service]
Type=simple
User=baseball-trajectory
WorkingDirectory=/opt/baseball-trajectory
ExecStart=/opt/baseball-trajectory/.venv/bin/shiny run baseball_trajectory.app:app --host 127.0.0.1 --port 8000
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target- 1
- What the unit is and when it starts.
- 2
-
Name shown by
systemctl status. - 3
- Start after networking is up.
- 4
- How to run the process.
- 5
-
The
ExecStartprocess is the service. - 6
-
Run as the service account, not
root. - 7
- Directory the process starts in.
- 8
- Absolute path into the venv; loopback only.
- 9
- Restart after a crash.
- 10
- Wait 5 seconds between restarts.
- 11
-
What
enablehooks into. - 12
- Start at a normal boot.
What the unit file does
Three directives and one argument control how the service runs: User, ExecStart (and its --host argument), and Restart.
User=baseball-trajectoryruns the process as the service account from Linux Users, notroot. The app only serves requests and calls an external API, so that account needs no extra privilege at all.
ExecStartuses the absolute path into the venv. There’s no shell involved, noPATHto search, and no activation step. If this path is wrong the unit fails instantly, and it’s the most common cause of a failed first start.--host 127.0.0.1binds the app to loopback only. Change it to0.0.0.0and the app is reachable from the internet without TLS and without the proxy, which is exactly what we don’t want.
Restart=on-failurewithRestartSec=5brings the app back after a crash, waiting five seconds between attempts so a fast crash loop doesn’t spin the CPU.
Editing the file with vim
vim is already on AL2023 (which vim prints /usr/bin/vim). You don’t have to know much vim to write a unit file, but it helps to know that it has modes. It opens in Normal mode, where every key is a command, not text. Insert mode is where typing puts characters in the file. Most vim confusion comes from typing in the wrong mode.
sudo vim opens the new, empty file. The cursor sits on the first line, each ~ marks a line past the end of the file, and the bottom line shows the file name and [New]:
From there:
Press i to switch to Insert mode. The bottom line changes to
-- INSERT --.Paste the unit file from above. In most Linux terminals that’s Ctrl+Shift+V (on macOS it’s Cmd+V). Typing it works too.
Press Esc to return to Normal mode.
-- INSERT --disappears.vimcolors the keys and values because it recognizes asystemdunit file. If the bottom line saysType :qa! and press <Enter> to abandon all changes and exit Vim, you pressed Ctrl+C in Normal mode. It’s only a hint (nothing was lost, so carry on with step 4).Type
:wqand press Enter. The colon opens a command line at the bottom of the screen;wwrites the file andqquits.
If the pasted lines come out indented in a staircase, vim auto-indented the paste. Press Esc, type :q! and Enter to quit without saving, then reopen the file and run :set paste before pressing i.
A few more keys cover most mistakes:
vim keys
| Keys (Normal mode) | What it does |
|---|---|
:q! |
Quit without saving |
:w |
Save and keep editing |
u |
Undo the last change |
dd |
Delete the current line |
x |
Delete the character under the cursor |
gg / G |
Jump to the first / last line |
Two messages are worth knowing ahead of time:
E212: Can't open file for writing:vimwas started withoutsudo, and onlyrootcan write to/etc/systemd/system.- Fix: Quit with
:q!and rerunsudo vim.
- Fix: Quit with
E325: ATTENTION ... Found a swap file: an earliervimsession on this file didn’t exit cleanly (often a dropped SSH connection).- Fix: Press E to edit anyway, or D to delete the old swap file if
vimoffers it.
- Fix: Press E to edit anyway, or D to delete the old swap file if
Back at the shell prompt, print the file to confirm it saved:
sudo cat /etc/systemd/system/baseball-trajectory.serviceThe output should match the unit file above, line for line. nano is also installed and shows its key commands at the bottom of the screen (Ctrl+O saves, Ctrl+X exits), so sudo nano works as well.
Start the service
Load the new file and start the service:
sudo systemctl daemon-reloaddaemon-reload tells systemd to reread the unit files on disk.
sudo systemctl enable --now baseball-trajectoryCreated symlink /etc/systemd/system/multi-user.target.wants/baseball-trajectory.service → /etc/systemd/system/baseball-trajectory.service.enableregisters the unit to start on boot.
--nowstarts it immediately so we don’t have to runstartseparately.
- The symlink is what “enabled” means on disk:
- the unit’s
WantedBy=multi-user.targetline tellssystemdto link it intomulti-user.target.wants/.
- Everything linked here starts when the instance boots.
disableremoves the link.
- the unit’s
Confirming it actually came up
Never trust enable --now to mean the app is running. It means systemd tried.
sudo systemctl status baseball-trajectory --no-pagerTwo things to read here:
Active: active (running)is the state, and
enabledin theLoaded:line is the confirmation it will come back after a reboot
A unit can be running and not enabled, which works fine until the instance restarts.
Also worth noting:
preset: disabledonly means the operating system wouldn’t enable this unit on its own (ourenableoverrides it).
Memory: 182.3Mis worth a glance on at3.micro, which has 1 GB in total (see Instance Size).
Then confirm something is actually listening, from the instance itself:
curl -I http://127.0.0.1:8000HTTP/1.1 200 OK
date: Tue, 24 Nov 2026 06:01:13 GMT
server: uvicorn
content-length: 9819
content-type: text/html; charset=utf-8A 200 means the landing page rendered. A redirect is fine too. Connection refused means the process died between status and curl, and the journal will say why:
sudo journalctl -u baseball-trajectory -n 50 --no-pagerNov 24 05:53:37 ip-xxx-xx-xx-xx.ec2.internal systemd[1]: Started baseball-trajectory.service - baseball-trajectory.
Nov 24 05:53:39 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: mkdir -p failed for path /home/baseball-trajectory/.config/matplotlib: [Errno 13] Permission denied: '/home/baseball-trajectory'
Nov 24 05:53:39 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: Matplotlib created a temporary cache directory at /tmp/matplotlib-ldz8gu0b because there was an issue with the default path (/home/baseball-trajectory/.config/matplotlib); it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
Nov 24 05:53:40 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Started server process [208804]
Nov 24 05:53:40 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Waiting for application startup.
Nov 24 05:53:40 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Application startup complete.
Nov 24 05:53:40 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Nov 24 06:01:13 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: 127.0.0.1:34292 - "HEAD / HTTP/1.1" 200 OK-ufilters to this unit
-n 50limits it to the last 50 lines, and
--no-pagerdumps it straight to the terminal instead of openingless
When we want to watch a start attempt live, journalctl -u baseball-trajectory -f follows the log the same way tail -f does.
Fixing the Matplotlib cache warning
The service is running, but the second and third lines of the journal show a problem: Matplotlib stores its font cache and settings in ~/.config/matplotlib, and for the service account that’s /home/baseball-trajectory. useradd -r never created that folder (see “User vs. Service Accounts” above), so mkdir fails with Permission denied.
Matplotlib recovers by creating a new folder in /tmp on every start, which is why the app still works. The cost is a rebuilt font cache on each restart and the same warning in the journal every time. The warning also names the fix: set MPLCONFIGDIR to a folder the service account can write to.
systemd can create that folder for us. Open the unit file again:
sudo vim /etc/systemd/system/baseball-trajectory.serviceAdd two lines to the end of the [Service] section (move the cursor to the RestartSec=5 line, press o to open a new line below it in Insert mode, type the lines, then Esc and :wq):
[Service]
Type=simple
User=baseball-trajectory
WorkingDirectory=/opt/baseball-trajectory
ExecStart=/opt/baseball-trajectory/.venv/bin/shiny run baseball_trajectory.app:app --host 127.0.0.1 --port 8000
Restart=on-failure
RestartSec=5
CacheDirectory=baseball-trajectory
Environment=MPLCONFIGDIR=/var/cache/baseball-trajectory- 1
-
CacheDirectory=baseball-trajectorytellssystemdto create/var/cache/baseball-trajectorybefore the service starts, owned by theUser=account. - 2
-
Environment=MPLCONFIGDIR=...sets the variable for the app’s process only, so Matplotlib writes there instead of the missing home folder.
With both lines typed, still in Insert mode, the unit file looks like this:
Press Esc, then type :wq and press Enter to save:
This keeps the service account’s shape intact. It still has no home folder and owns nothing under /opt; it owns only its cache.
Reload the unit files and restart the service so it picks up the change:
sudo systemctl daemon-reloadsudo systemctl restart baseball-trajectoryWe’ll confirm systemd created the folder with the right owner:
ls -ld /var/cache/baseball-trajectorydrwxr-xr-x. 2 baseball-trajectory baseball-trajectory 35 Nov 24 06:33 /var/cache/baseball-trajectoryThe service account owns the folder, which systemd created on the restart.
Finally, we’ll check the journal again. The mkdir -p failed and MPLCONFIGDIR lines should be gone from the new start:
sudo journalctl -u baseball-trajectory -n 10 --no-pagerNov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Application shutdown complete.
Nov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal shiny[208804]: INFO: Finished server process [208804]
Nov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal systemd[1]: baseball-trajectory.service: Deactivated successfully.
Nov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal systemd[1]: Stopped baseball-trajectory.service - baseball-trajectory.
Nov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal systemd[1]: baseball-trajectory.service: Consumed 7.281s CPU time.
Nov 24 06:33:20 ip-xxx-xx-xx-xx.ec2.internal systemd[1]: Started baseball-trajectory.service - baseball-trajectory.
Nov 24 06:33:24 ip-xxx-xx-xx-xx.ec2.internal shiny[210169]: INFO: Started server process [210169]
Nov 24 06:33:24 ip-xxx-xx-xx-xx.ec2.internal shiny[210169]: INFO: Waiting for application startup.
Nov 24 06:33:24 ip-xxx-xx-xx-xx.ec2.internal shiny[210169]: INFO: Application startup complete.
Nov 24 06:33:24 ip-xxx-xx-xx-xx.ec2.internal shiny[210169]: INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)The old process (208804) shut down cleanly, and the new one (210169) started with no mkdir -p failed or MPLCONFIGDIR warning between Started and Started server process.
Viewing the app
curl -I proves the app answers, but we still haven’t seen it. The app listens on 127.0.0.1, and the security group only opens port 22, so a browser on our local machine can’t reach it directly. An SSH tunnel gets around both without opening a port. SSH forwards a port on our local machine through the connection we already use, to a port on the instance:
%%{init: {'theme': 'base', 'themeVariables': {'fontFamily': 'monospace', 'fontSize':'13px'}}}%%
sequenceDiagram
participant B as Browser
participant L as ssh<br/>local :8000
participant S as sshd<br/>instance :22
participant A as app<br/>127.0.0.1:8000
B->>L: GET localhost:8000
L->>S: SSH tunnel
S->>A: GET /
A-->>S: 200 OK
S-->>L: SSH tunnel
L-->>B: the app
Run this from our local machine, not the instance:
ssh -N -L 8000:127.0.0.1:8000 \
-i ~/.ssh/aws-dev.pem -o IdentitiesOnly=yes -o IdentityAgent=none \
ec2-user@YOUR_PUBLIC_IP_ADDRESS-L 8000:127.0.0.1:8000 reads as local port 8000, sent to 127.0.0.1:8000 as seen from the instance. -N tells SSH not to open a shell, so the terminal sits quietly while the tunnel is open. With the aws-dev entry from SSH config, the same command is ssh -N -L 8000:127.0.0.1:8000 aws-dev. If something on our local machine already uses 8000, pick another local port (-L 8001:127.0.0.1:8000) and use it in the browser.
Now open http://localhost:8000 in a browser:
The tunnel only works for whoever holds the SSH key, and it closes with Ctrl+C. That’s fine for checking our own work. Giving other people access takes a proxy, which Accessibility sets up with nginx.
Recap
A third party app gets its own tree under
/opt: the source and a virtual environment built from the/optPython, never the system copy.The install spreads across four locations by purpose: the app under
/opt, the unit file under/etc/systemd/system, logs injournald, and a cache under/var/cache.baseball-trajectorykeeps no state on disk, so it has no/var/libentry, but it needs outbound HTTPS at install time and at runtime.Confirm the console script starts from the venv and answers on
127.0.0.1:8000before handing it tosystemd.The
baseball-trajectoryunit runs as its own service account (User=), starts from an absoluteExecStartpath into the venv, binds to127.0.0.1so only nginx can reach it, and restarts on failure.After
systemctl enable --now, confirm withsystemctl status(active (running)andenabled) andcurl -I http://127.0.0.1:8000, and readjournalctl -u baseball-trajectoryeven when both look fine. Warnings like Matplotlib’s missing home folder only show up there.A service account has no home folder, so anything the app expects to write under
~needs a folder of its own.CacheDirectory=creates one with the right owner, andEnvironment=points the app at it.An SSH tunnel (
ssh -N -L 8000:127.0.0.1:8000) shows the app in our own browser without opening a port. Other people reach it throughnginx, set up in Accessibility.
![vim showing an empty file with the status line /etc/systemd/system/baseball-trajectory.service [New]](img/install-real-app-vim-new-file.png)





