使用 Capistrano 3 将 Symfony2 部署到生产环境
Symfony2 deployment to production using Capistrano 3
在了解了一些本地 Symfony2 开发之后,我想探索如何部署到实时环境,我决定尝试 Capistrano 3 和 Symfony 插件 https://github.com/capistrano/symfony/。
我遵循了许多指南并阅读了很多 SO questions/answers 并且我能够将我的文件放到实时服务器上。
我在共享计划中使用 Dreamhost,并且有一个 Web 目录 home/myusername/mydomain/web。在 Capistrano 部署后 home/myusername/mydomain 的目录如下所示:
当前/
发布/
回购/
共享/
tmp/
web/ <--这不是 Symfony 网络目录,而是由 Dreamhost 默认创建的。
然而,当我访问我的路由工作站点 none 时,我只收到 404。如果我将文档根目录从 /home/myusername/pickingorganic/web 更改为 /home/myusername/pickingorganic/ 然后我可以访问我的路由,例如 mydomain/current/web/login,但显然我不希望 current/web 出现在URL.
如果我运行
ls -la mydomain | grep "\->"
在服务器上,我可以看到来自当前目录的 Capistano 符号链接似乎正确
current -> /home/myusername/mydomain/releases/20160112132605
我假设我的错误出在 Symfony web/.htaccess 文件(未修改)或我的 Capistrano 设置中。我把这些放在下面了。非常感谢任何关于我哪里出错的建议。另外,如果有人有使用 Capistrano Symphony 插件的经验,尤其是如何正确配置此处 https://github.com/capistrano/symfony/#settings 显示的设置,那就太棒了;我已经搜索过示例或教程,但没有真正找到任何东西。
deploy.rb
# config valid only for current version of Capistrano
lock '3.4.0'
#set :tmp_dir, "#{fetch(:home)}/tmp"
set :tmp_dir, "/home/myusername/mydomain/tmp"
set :application, 'storyproject'
set :repo_url, 'git@github.com:githubid/githubproject-project.git'
# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/home/myusername/mydomain'
# Default value for :scm is :git
set :scm, :git
# Default value for :format is :pretty
# set :format, :pretty
# Default value for :log_level is :debug
# set :log_level, :debug
# Default value for :pty is false
# set :pty, true
# Default value for :linked_files is []
set :linked_files, fetch(:linked_files,
[]).push('app/config/parameters.yml')
# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, []).push('vendor/bundle')
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# Default value for keep_releases is 5
# set :keep_releases, 5
#namespace :deploy do
# after :restart, :clear_cache do
# on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
# end
#end
#end
namespace :deploy do
desc 'composer install'
task :composer_install do
on roles(:web) do
within release_path do
execute 'composer', 'install', '--no-dev', '--optimize- autoloader'
end
end
end
after :updated, 'deploy:composer_install'
desc 'Restart application - does nothing, see comments below'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# This is present b/c 'cap production deploy' is blowing up w/o it.
# Not sure what's up with that, the Google hasn't helped, and I'm tired
# of screwing with it. It stays in for now.
end
end
end
production.rb
set :stage, :production
role :web, %w{sshuser@mydomain}
role :app, %w{sshuser@mydomain}
set :ssh_options, {
forward_agent: true
}
# Symfony environment
set :symfony_env, "prod"
# Symfony application path
set :app_path, "app"
# Symfony web path
set :web_path, "web"
# Symfony log path
set :log_path, fetch(:app_path) + "/logs"
# Symfony cache path
set :cache_path, fetch(:app_path) + "/cache"
# Symfony config file path
set :app_config_path, fetch(:app_path) + "/config"
# Controllers to clear
set :controllers_to_clear, ["app_*.php"]
# Files that need to remain the same between deploys
#set :linked_files, []
# Dirs that need to remain the same between deploys (shared dirs)
set :linked_dirs, [fetch(:log_path), fetch(:web_path) + "/uploads"]
# Dirs that need to be writable by the HTTP Server (i.e. cache, log dirs)
set :file_permissions_paths, [fetch(:log_path), fetch(:cache_path)]
# Name used by the Web Server (i.e. www-data for Apache)
set :file_permissions_users, ['www-data']
# Name used by the Web Server (i.e. www-data for Apache)
set :webserver_user, "www-data"
# Method used to set permissions (:chmod, :acl, or :chgrp)
set :permission_method, false
# Execute set permissions
set :use_set_permissions, false
# Symfony console path
set :symfony_console_path, fetch(:app_path) + "/console"
# Symfony console flags
set :symfony_console_flags, "--no-debug"
# Assets install path
set :assets_install_path, fetch(:web_path)
# Assets install flags
set :assets_install_flags, '--symlink'
# Assetic dump flags
set :assetic_dump_flags, ''
fetch(:default_env).merge!(symfony_env: fetch(:symfony_env))
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
# server 'example.com', user: 'deploy', roles: %w{app db web}, my_property: :my_value
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
Symfony web/.htaccess
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the app.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}:: ^(/.+)/(.*)::$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by apache
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/app.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/ [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
# Rewrite all other queries to the front controller.
RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 302 ^/$ /app.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>
文件夹结构如下所示:
├── current -> /home/myusername/mydomain/releases/20150120114500/
├── releases
│ ├── 20150080072500
│ ├── 20150090083000
│ ├── 20150100093500
│ ├── 20150110104000
│ └── 20150120114500
├── repo
│ └── <VCS related data>
├── revisions.log
└── shared
└── <linked_files and linked_dirs>
来自文档:
current is a symlink pointing to the latest release. This symlink is updated at the end of a successful deployment. If the deployment fails in any step the current symlink still points to the old release.
您的 app.php
主文件位于 /home/myusername/mydomain/current/web/app.php
中,您应该将您的域准确指向该目录,否则您必须在路径中添加目录才能访问该文件(例如 mydomain.com/myusername/mydomain/current/web
).
只需将您的域指向 /home/myusername/mydomain/current/web/
。
对于 Apache,您必须确保启用了以下符号链接。
<Directory /home/myusername/mydomain>
Options FollowSymLinks
</Directory>
在了解了一些本地 Symfony2 开发之后,我想探索如何部署到实时环境,我决定尝试 Capistrano 3 和 Symfony 插件 https://github.com/capistrano/symfony/。
我遵循了许多指南并阅读了很多 SO questions/answers 并且我能够将我的文件放到实时服务器上。
我在共享计划中使用 Dreamhost,并且有一个 Web 目录 home/myusername/mydomain/web。在 Capistrano 部署后 home/myusername/mydomain 的目录如下所示:
当前/
发布/
回购/
共享/
tmp/
web/ <--这不是 Symfony 网络目录,而是由 Dreamhost 默认创建的。
然而,当我访问我的路由工作站点 none 时,我只收到 404。如果我将文档根目录从 /home/myusername/pickingorganic/web 更改为 /home/myusername/pickingorganic/ 然后我可以访问我的路由,例如 mydomain/current/web/login,但显然我不希望 current/web 出现在URL.
如果我运行
ls -la mydomain | grep "\->"
在服务器上,我可以看到来自当前目录的 Capistano 符号链接似乎正确
current -> /home/myusername/mydomain/releases/20160112132605
我假设我的错误出在 Symfony web/.htaccess 文件(未修改)或我的 Capistrano 设置中。我把这些放在下面了。非常感谢任何关于我哪里出错的建议。另外,如果有人有使用 Capistrano Symphony 插件的经验,尤其是如何正确配置此处 https://github.com/capistrano/symfony/#settings 显示的设置,那就太棒了;我已经搜索过示例或教程,但没有真正找到任何东西。
deploy.rb
# config valid only for current version of Capistrano
lock '3.4.0'
#set :tmp_dir, "#{fetch(:home)}/tmp"
set :tmp_dir, "/home/myusername/mydomain/tmp"
set :application, 'storyproject'
set :repo_url, 'git@github.com:githubid/githubproject-project.git'
# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/home/myusername/mydomain'
# Default value for :scm is :git
set :scm, :git
# Default value for :format is :pretty
# set :format, :pretty
# Default value for :log_level is :debug
# set :log_level, :debug
# Default value for :pty is false
# set :pty, true
# Default value for :linked_files is []
set :linked_files, fetch(:linked_files,
[]).push('app/config/parameters.yml')
# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, []).push('vendor/bundle')
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# Default value for keep_releases is 5
# set :keep_releases, 5
#namespace :deploy do
# after :restart, :clear_cache do
# on roles(:web), in: :groups, limit: 3, wait: 10 do
# Here we can do anything such as:
# within release_path do
# execute :rake, 'cache:clear'
# end
# end
#end
#end
namespace :deploy do
desc 'composer install'
task :composer_install do
on roles(:web) do
within release_path do
execute 'composer', 'install', '--no-dev', '--optimize- autoloader'
end
end
end
after :updated, 'deploy:composer_install'
desc 'Restart application - does nothing, see comments below'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# This is present b/c 'cap production deploy' is blowing up w/o it.
# Not sure what's up with that, the Google hasn't helped, and I'm tired
# of screwing with it. It stays in for now.
end
end
end
production.rb
set :stage, :production
role :web, %w{sshuser@mydomain}
role :app, %w{sshuser@mydomain}
set :ssh_options, {
forward_agent: true
}
# Symfony environment
set :symfony_env, "prod"
# Symfony application path
set :app_path, "app"
# Symfony web path
set :web_path, "web"
# Symfony log path
set :log_path, fetch(:app_path) + "/logs"
# Symfony cache path
set :cache_path, fetch(:app_path) + "/cache"
# Symfony config file path
set :app_config_path, fetch(:app_path) + "/config"
# Controllers to clear
set :controllers_to_clear, ["app_*.php"]
# Files that need to remain the same between deploys
#set :linked_files, []
# Dirs that need to remain the same between deploys (shared dirs)
set :linked_dirs, [fetch(:log_path), fetch(:web_path) + "/uploads"]
# Dirs that need to be writable by the HTTP Server (i.e. cache, log dirs)
set :file_permissions_paths, [fetch(:log_path), fetch(:cache_path)]
# Name used by the Web Server (i.e. www-data for Apache)
set :file_permissions_users, ['www-data']
# Name used by the Web Server (i.e. www-data for Apache)
set :webserver_user, "www-data"
# Method used to set permissions (:chmod, :acl, or :chgrp)
set :permission_method, false
# Execute set permissions
set :use_set_permissions, false
# Symfony console path
set :symfony_console_path, fetch(:app_path) + "/console"
# Symfony console flags
set :symfony_console_flags, "--no-debug"
# Assets install path
set :assets_install_path, fetch(:web_path)
# Assets install flags
set :assets_install_flags, '--symlink'
# Assetic dump flags
set :assetic_dump_flags, ''
fetch(:default_env).merge!(symfony_env: fetch(:symfony_env))
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
# server 'example.com', user: 'deploy', roles: %w{app db web}, my_property: :my_value
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
# set :ssh_options, {
# keys: %w(/home/rlisowski/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(password)
# }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server 'example.com',
# user: 'user_name',
# roles: %w{web app},
# ssh_options: {
# user: 'user_name', # overrides user setting above
# keys: %w(/home/user_name/.ssh/id_rsa),
# forward_agent: false,
# auth_methods: %w(publickey password)
# # password: 'please use keys'
# }
Symfony web/.htaccess
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the app.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}:: ^(/.+)/(.*)::$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by apache
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/app.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/ [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
# Rewrite all other queries to the front controller.
RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 302 ^/$ /app.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>
文件夹结构如下所示:
├── current -> /home/myusername/mydomain/releases/20150120114500/
├── releases
│ ├── 20150080072500
│ ├── 20150090083000
│ ├── 20150100093500
│ ├── 20150110104000
│ └── 20150120114500
├── repo
│ └── <VCS related data>
├── revisions.log
└── shared
└── <linked_files and linked_dirs>
来自文档:
current is a symlink pointing to the latest release. This symlink is updated at the end of a successful deployment. If the deployment fails in any step the current symlink still points to the old release.
您的 app.php
主文件位于 /home/myusername/mydomain/current/web/app.php
中,您应该将您的域准确指向该目录,否则您必须在路径中添加目录才能访问该文件(例如 mydomain.com/myusername/mydomain/current/web
).
只需将您的域指向 /home/myusername/mydomain/current/web/
。
对于 Apache,您必须确保启用了以下符号链接。
<Directory /home/myusername/mydomain>
Options FollowSymLinks
</Directory>