如何在Azure VM(v1)上设置全局可见的环境变量

2024-06-16 11:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以在使用Ubuntu操作系统的azurevm(服务管理)上设置系统范围/全局可见的环境变量?我陷入了这样一种情况:在ubuntu的/etc/environment/etc/profile和{}中设置它们,而我的应用程序代码却没有选择它们。然而,它们确实出现在printenv上。我的猜测是,由于我的web服务器的设置方式(Gunicorn+Nginx反向代理),它们在某种程度上被绕过了。在

但也许有一种方法可以在azurevm上设置优先于所有内容的env变量?我知道Heroku在他们的仪表板中有这个选项(我一直在使用),Azure Web应用也有这个选项(我无法使用它,因为有各种各样的兼容性问题)。在


Tags: 方法webenvironmentubuntu系统选项环境变量etc
1条回答
网友
1楼 · 发布于 2024-06-16 11:39:16

作为参考,我在azurevm上发布了我的步骤。你可以检查一下和你的比较。在

  1. 连接到新的Azure虚拟机:ssh user@vm-name.cloudapp.net
  2. 安装工具pipvirtualenv

    sudo apt-get update
    sudo apt-get install python-pip
    sudo pip install virtualenv
    
  3. 准备virtualenv以安装gunicorndjango

    mkdir environments
    virtualenv environments/experiment/ 
    cd environments/experiment/ 
    source bin/activate 
    pip install gunicorn django
    
  4. 创建一个django项目并使用gunicorn运行它并尝试访问它:

    django-admin startproject mysite
    bin/gunicorn  chdir=mysite -w 3  env DJANGO_SETTINGS_MODULE=mysite.settings mysite.wsgi:application
    # using w3m to access http://localhost:8000
    w3m http://localhost:8000
    
  5. 安装Nginx并配置反向代理:

    sudo apt-get install nginx
    sudo cp /etc/nginx/site-available/default /etc/nginx/site-available/default.bak
    sudo vim /etc/nginx/site-available/default
    

下面是nginx的default文件中配置的内容:

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /usr/share/nginx/html;
        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules

                include proxy_params;
                proxy_pass http://unix:/home/<user>/environments/experiment/mysite/mysite.sock; 
                # I also try to config `http://localhost:8000;`, it's ok too.
        }
  }

我也尝试配置proxy_pass http://localhost:8000;,这也没问题。在

  1. 重新启动nginx服务并重新启动gunicorn

    sudo service nginx restart
    bin/gunicorn  chdir=mysite  bind unix:/home/<user>/environments/experiment/mysite/mysite.sock -w 3  env DJANGO_SETTINGS_MODULE=mysite.settings mysite.wsgi:application
    

我发现应用程序启动后无法设置环境变量。所以请在启动gunicorn之前运行source /etc/...命令。在

有任何问题,请随时告诉我。在

相关问题 更多 >