Ubuntu下Fortran项目部署上线流程
在Ubuntu上部署Fortran项目前,需先安装Fortran编译器。gfortran(GNU Fortran Compiler)是Ubuntu默认的Fortran编译器,支持大多数Fortran标准(如Fortran 90/95/2003/2008)。
通过以下命令安装最新版gfortran:
sudo apt update && sudo apt install gfortran -y
安装完成后,验证编译器是否可用:
gfortran --version
输出应显示gfortran版本信息(如GNU Fortran (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0)。
对于单个Fortran源文件(如hello.f90),可直接使用gfortran编译为可执行文件:
gfortran -o hello hello.f90
-o hello:指定输出可执行文件名为hello;hello.f90:源代码文件。./hello
输出Hello, World!即表示编译运行成功。
fpm(Fortran Package Manager)是Fortran生态官方推荐的构建工具,可自动化处理依赖、编译和打包。
wget https://github.com/fortran-lang/fpm/releases/download/v0.9.0/fpm-0.9.0-linux-x86_64.tar.gz
tar -xzf fpm-0.9.0-linux-x86_64.tar.gz
sudo mv fpm-0.9.0-linux-x86_64 /usr/local/bin/fpm # 移动至系统路径
fpm new my_fortran_project # 创建名为my_fortran_project的目录
cd my_fortran_project
fpm build # 编译项目(生成可执行文件位于./build/gfortran_*/my_fortran_project)
fpm run # 运行项目
fpm会自动处理依赖(如项目中引用的其他Fortran库),简化构建流程。
将编译好的可执行文件、依赖库及配置文件打包。若程序为静态链接(无外部依赖),直接打包可执行文件即可;若为动态链接,需包含依赖库(通过ldd命令查看):
ldd hello > dependencies.txt # 记录依赖库
tar -czvf my_fortran_app.tar.gz hello dependencies.txt README.md # 打包
使用scp(Secure Copy)将打包文件上传到目标Ubuntu服务器:
scp my_fortran_app.tar.gz username@server_ip:/path/to/deploy
其中username为服务器用户名,server_ip为服务器IP地址,/path/to/deploy为目标目录。
cd /path/to/deploy
tar -xzvf my_fortran_app.tar.gz
chmod +x hello
LD_LIBRARY_PATH),需在~/.bashrc或/etc/profile中添加:export LD_LIBRARY_PATH=/path/to/deploy/libs:$LD_LIBRARY_PATH
source ~/.bashrc
./hello
sudo nano /etc/systemd/system/my_fortran_service.service
写入以下内容(替换/path/to/deploy/hello为实际路径):[Unit]
Description=My Fortran Application
After=network.target
[Service]
ExecStart=/path/to/deploy/hello
Restart=always
User=username # 替换为运行程序的用户
[Install]
WantedBy=multi-user.target
保存后,启动服务并设置开机自启:sudo systemctl start my_fortran_service
sudo systemctl enable my_fortran_service
查看服务状态:sudo systemctl status my_fortran_service
sudo apt install libnetcdf-dev),或使用fpm的--deps选项指定依赖。update-alternatives切换gfortran版本)。ufw)允许对应端口,禁用root登录(修改/etc/ssh/sshd_config中的PermitRootLogin no),并安装fail2ban防止暴力破解。