0

I run a Next.js frontend on a VM using systemd. My workflow for making systemd services is usually:

  1. Make the application work from the user shell (ec2-user in this case)
  2. Write a unit file which does the same, and uses the same user

However, the service did not work as expected, due to differences in $PATH.

Indeed, .bash_profile and .bashrc contain code that extends $PATH. This configuration has been done automatically by tools like pyenv.

So I ended up making an ugly unit file to match the same $PATH that I have in my user shell:

[Unit]
Description=Web App Frontend
After=network.target

[Service]
User=ec2-user
Group=ec2-user
Environment="PATH=/home/ec2-user/.pyenv/shims:/home/ec2-user/.pyenv/bin:/home/ec2-user/.nvm/versions/node/v20.11.0/bin:/home/ec2-user/.local/bin:/home/ec2-user/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin"
WorkingDirectory=/home/ec2-user/web-app-frontend
ExecStart=/home/ec2-user/.nvm/versions/node/v20.11.0/bin/yarn start

[Install]
WantedBy=multi-user.target

Is there a cleaner way to solve this?

1 Answer 1

0

Answer was provided by user Sienna Dragon on SO. I'm copying their answer below:

It seems that you want your systemd service to have the same environment as when you open a termina. You can achieve this using PAM (Pluggable Authentication Modules) to load the user's environment. Just add PAMName=login to your .service file. Like this :

[Service]
PAMName=login
Type=simple
ExecStart=/path/to/your/command

This will enables your systemd load envirment using PAM login module.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.