Start Rails server from within Rails - ruby-on-rails

Is it possible to start a rails server from within a running rails server?
I would also like to install the gems using 'bundle install'.
I made a simple setup, but when i invoke 'bundle install', the gems from the running rails server are installed and not the gems for the server i wish to start.
What would be the best strategy to launch another rails server.

As others have stated in the comments, you can spawn shell commands from your Rails application. You have several options. http://mentalized.net/journal/2010/03/08/5_ways_to_run_commands_from_ruby/
If you want to inherit the user environment when running bundle commands, you might want to spawn a bash login shell then run the command. E.g. ```/bin/bash -l -c "command here".
Although you didn't ask about killing them, if you're only going to run this and you're not building anything to keep track of process IDs, you could find and kill other instances with some ps aux | awk '/process name or unique path/ {print $2}' | xargs kill magic

Related

Run `rails c` on GCloud instace with appengine gem

I have a Rails 6.0.0.rc1 application (with the appengine gem install) that I deployed to GCP. Is there a way to log into a remote rails console on the instance that runs the application? I tried this:
bundle exec rake appengine:exec -- bundle exec rails c
which gives the following output:
...
---------- EXECUTE COMMAND ----------
bundle exec rails c
Loading production environment (Rails 6.0.0.rc1)
Switch to inspect mode.
...
so apparently it executed the command, but closes the connection right after.
Is there an easy way to do this?
As reference: On Heroku this would simply be:
heroku run rails c --app my-application
There's a few steps involved:
https://gist.github.com/kyptin/e5da270a54abafac2fbfcd9b52cafb61
If you're running a Rails app in Google App Engine's flexible environment, it takes a bit of setup to get to a rails console attached to your deployed environment. I wanted to document the steps for my own reference and also as an aid to others.
Open the Google App Engine -> instances section of the Google Cloud Platform (GCP) console.
Select the "SSH" drop-down for a running instance. (Which instance? Both of my instances are in the same cluster, and both are running Rails, so it didn't matter for me. YMMV.) You have a choice about how to connect via ssh.
Choose "Open in browser window" to open a web-based SSH session, which is convenient but potentially awkward.
Choose "View gcloud command" to view and copy a gcloud command that you can use from a terminal, which lets you use your favorite terminal app but may require the extra steps of installing the gcloud command and authenticating the gcloud command with GCP.
When you're in the SSH session of your choice, run sudo docker ps to see what docker containers are presently running.
Identify the container of your app. Here's what my output looked like (abbreviated for easier reading). My app's container was the first one.
jeff#aef-default-425eaf...hvj:~$ sudo docker ps
CONTAINER ID IMAGE COMMAND NAMES
38e......552 us.gcr.io/my-project/appengine/default... "/bin/sh -c 'exec bun" gaeapp
8c0......0ab gcr.io/google_appengine/cloud-sql-proxy "/cloud_sql_proxy -di" focused_lalande
855......f92 gcr.io/google_appengine/api-proxy "/proxy" api
7ce......0ce gcr.io/google_appengine/nginx-proxy "/var/lib/nginx/bin/s" nginx_proxy
25f......bb8 gcr.io/google_appengine/fluentd-logger "/opt/google-fluentd/" fluentd_logger
Note the container name of your app (gaeapp in my case), and run container_exec bash.
Add ruby and node to your environment: export PATH=$PATH:/rbenv/versions/2.3.4/bin:/rbenv/bin:/nodejs/bin
cd /app to get to your application code.
Add any necessary environment variables that your Rails application expects to your environment. For example: export DATABASE_URL='...'
If you don't know what your app needs, you can view the full environment of the app with cat app.yaml.
bin/rails console production to start a Rails console in the Rails production environment.

Can't stop rails server

I am new to rails and I am using an ubuntu machine and the rubymine IDE. The problem is that I am unable to stop the rails server. I tried to stop the server by killing the rails process. But, when I run pgrep -l rails, no such process is found. So, I am only able to kill ruby processes, but, the server won't stop.
I tried ./script/server stop (since I started it by running ./script/server start), but, that didn't work. Googling around and finding some stackoverflow posts, I tried to change the localhost port's listening port but without success. Could someone help?
You can use other ports like the following:
rails server -p 3001
Normally in your terminal you can try Ctrl + C to shutdown the server.
The other way to kill the Ruby on Rails default server (which is WEBrick) is:
kill -INT $(cat tmp/pids/server.pid)
In your terminal to find out the PID of the process:
$ lsof -wni tcp:3000
Then, use the number in the PID column to kill the process:
For example:
$ kill -9 PID
And some of the other answers i found is:
To stop the rails server while it's running, press:
CTRL-C
CTRL-Z
You will get control back to bash. Then type (without the $):
$ fg
And this will go back into the process, and then quit out of Rails s properly.
It's a little annoying, but this sure beats killing the process manually. It's not too bad and it's the best I could figure out.
Updated answer:
You can use killall -9 rails to kill all running apps with "rails" in the name.
killall -9 rails
you can use grep command in following way,
ps aux | grep rails
and then
kill -9 {process_id}
pkill -9 rails to kill all the process of rails
Updated answer
ps aux|grep 'rails'|grep -v 'grep'|awk '{ print $2 }'|xargs kill -9
This will kill any running rails process. Replace 'rails' with something else to kill any other processes.
On my MAC the killall -9 rails does not work. But killall -9 ruby does.
Following are steps to kill server process:
1. lsof -i tcp:3000
2. kill -9 1234
where 1234 is the PID of process: localhost:3000 display in step 1.
OR
Remove file(server.pid) under Rails.root/tmp/pids/ and restart server.
OR
open app in another port by using command:
rails s -p 3001
I generally use:
killall ruby
OR
pkill -9 ruby
which will kill all ruby related processes that are running like rails server, rails console, etc.
1. Simply Delete the pid file from rails app directory
Rails_app -> tmp -> pids -> pid file
Delete the file and run
rails start
2. For Rails 5.0 and above, you can use this command
rails restart
If you are using a more modern version of Rails and it uses Puma as the web server, you can run the following command to find the stuck Puma process:
ps aux | grep puma
It will result in output similar to this:
85923 100.0 0.8 2682420 131324 s004 R+ 2:54pm 3:27.92 puma 3.12.0 (tcp://0.0.0.0:3010) [my-app]
92463 0.0 0.0 2458404 1976 s008 S+ 3:09pm 0:00.00 grep puma
You want the process that is not referring to grep. In this case, the process ID is 85923.
I can then run the following command to kill that process:
kill -9 85923
Use ctrl+c to shutdown your Webrick Server.
Unfortunately if its not works then forcefully close the terminal and restart it.
Another trick is that
1. open your system-monitor(a gui application) on ubuntu
2. Select processes tab
3. Then look for a process having name 'ruby'
4. End that process
Delete the server.pid from tmp/pids folder.
In my case, the error was: A server is already running. Check /home/sbhatta/myapp/tmp/pids/server.pid.
So, I delete server.pid
rm /home/sbhatta/myapp/tmp/pids/server.pid
then run rails s
Ctrl-Z should normally do the trick.
Step 1: find what are the items are consuming 3000 port.
lsof -i:3000
step 2 : Find the process named
For Mac
ruby TCP localhost:hbci (LISTEN)
For Ubuntu
ruby TCP *:3000 (LISTEN)
Step 3: Find the PID of the process and kill it.
kill -9 PID
it's as simple as
pkill -9 ruby
nothing more nothing less
I used killall -9 rails like Sri suggested and it didn't work. I adjusted the command to killall -9 ruby and the server closed immediately.
Tl;dr: killall -9 ruby
When the rails server does not start it means that it is already running then you can start by using new port eg.
rails s -p 3001
or it starts and stops in that case you want to delete temp folder in rails directory structure it starts the rails server.
check the /tmp/tmp/server.pid
there is a pid inside.
Usually, I ill do "kill -9 THE_PID" in the cmd
I have noticed on Windows (Im using 10 but not sure if the same for oler). If you use cmd.exe and ctrl + c the raisl server stops correctly.
However, if you use Git Bash, it doesn't. It says it has but when you look at the tmp pids, its still there.
Maybe a bug with git bash?
killall -9 ruby will kill all the ruby processes, and at-least on my machine, rails servers appear as ruby processes. killall -9 rails is much more specific and doesn't work for older versions of rails servers (it gives a 'rails:no process found' because the process is named ruby)
Encountered this problem a while ago. After submitting a form in activeadmin, the rails server just hanged and I was unable to kill it using normal means (even after ctrl+z it was still running in the background). Learner's answer helped, but this command doesn't need process id.
Follow these steps:
open your project
select in tmp folder
select pids folder
delete server.pid file
now start your rails server
On rails 6 using
ps aux | grep rails was not returning the server process
I had to do
ps aux | grep puma
to find the actual process and then kill it using
kill -9 {process_id}
It is late for this question.
Here is my 2 cents. I made a rake task for stopping the server when I don't have access to it.
I only tested on Mac though.
With this you can simply add it to your project then run the rake command.
Here you go:
Gist link: -latest version will be here.
https://gist.github.com/houmanka/289184ca5d8d92de0499#file-server-rake
Some code in here:
# Make a file under: `project_root/lib/tasks/server.rake`
# Then paste the following code
namespace :server do
desc "Stop the running server by killing the PID"
task :kill do
STDOUT.puts "Enter port number: "
post_number = STDIN.gets.strip
system "pid=$(lsof -i:#{post_number.to_i} -t); kill -TERM $pid || kill -KILL $pid"
end
end
# Then to use it in the terminal: `rake server:kill`
Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.
In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.
One super easy way would be
gem install shutup
then go in the current folder of your rails project and run
shutup # this will kill the Rails process currently running
You can use the command 'shutup' every time you want
DICLAIMER: I am the creator of this gem
NOTE: if you are using rvm install the gem globally
rvm #global do gem install shutup
For my windows 10 machine, Ctrl - C + Ctrl - D works.
We can kill rails session on Linux using PORT no
fuser -k 3000/tcp
here 3000 is a port no.
Now restart your server, you will see your server is in running state.
Just open the file using the location given
sudo vi /Users/user1/go/src/github.com/rails_app/rails_project/tmp/pids/server.pid
find the process_id / thread_id at which the process is runnning.
Kill the specified process / thread using kill -9 84699
Press Ctrl - C it will stop
if not check

cloudcontrol.com tcp port in use & procfile multiple commands & push hooks

i'm trying to get redmine running on cloudcontrol.com. i've got four questions:
i need to do more that start a webserver, for example i need to run rake tasks each time i deploy. can i put those in a one liner? i got the following in my Procfile for testing:
web: touch foobar; echo "barbarz"; bundle exec rails s -p $PORT -e production
but i neither see a file foobar nor do i get barbarz in the log files :(
When i login to the server and want to start the application it tells me tcp $PORT is already in use:
u24293#depvk7jw2mk-24293:~/www$ fuser $PORT/tcp # netstat and lsof is not available
24293/tcp: 10 13
u24293#depvk7jw2mk-24293:~/www$ ps axu | grep 13
u24293 13 0.0 0.0 52036 3268 ? SNs 15:22 0:00 sshd: u24293#pts/0
by sshd??? why would that be?
i need to change this default behaviour during push:
-----> Rails plugin injection
Injecting rails_log_stdout
Injecting rails3_serve_static_assets
or run something after it as easyredmine doesnt like plugins in vendor/plugins (or i cahnge the code of easyredmine quickly). how would i do that (not change the code, run an after hook for that like with capistrano or so)?
we have our own gitlab on a dedicated server and for bundle i need to pull those gems. how can i get the public key of the user running the app before the first deployment so i can add it to gitlab?
thanks in advance :)
The web command is only executed in the web containers. Using run bash connects you to a special ssh container of your app. See https://www.cloudcontrol.com/dev-center/Platform%20Documentation#secure-shell-ssh
Generally, you can not put multiple commands in one Procfile line. Wrap them in a sh -c '<cmd1>; <cmd2>' call or use a shell script explicitly.
Keep in mind that this script will be executed in each container being started. This includes the number of containers you deploy your app with and any redeploys that are triggered by the platform during operation (in case of a node failures, addon changes etc.).
In the ssh container the $PORT is used by the ssh server you are connected to.
If it is a problem of redmine during runtime, you could remove the plugins in the mentioned startup script. If it's a problem during the gem install currently you can not circumvent this behavior.
Dependencies requiring special ssh keys are not supported right now. If your server supports basic auth over https, you can use the https://<username>:<password>#hostname syntax

How to stop (and restart) the Rails Server?

I'm following the instructions here http://railsinstaller.org/mac to get up and running with Rails on a Mac running OS X 10.8.2
At step 8 I'm asked to restart Rails server but how?
I'm assuming via a command line, but from within the already open ruby terminal window or a new one?
Now in rails 5 you can do:
rails restart
The output of rails --tasks:
Restart app by touching tmp/restart.txt
I think that is usefully if you run rails as a demon
Press Ctrl+C
When you start the server it mentions this in the startup text.
On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):
alias restart_rails='kill -9 `cat tmp/pids/server.pid`; rails server -d'
My initial response to the comment by #zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d) sooner than the kill can actually cause the previous running instance to stop.
So alternatively, kill -9 cat tmp/pids/server.pid && rails server -d might be more robust; or you can specifically run the kill, wait for the tmp/pids folder to empty out, then restart your new server.
In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line
if you are not able to find the rails process to kill it might actually be not running. Delete the tmp folder and its sub-folders from where you are running the rails server and try again.
I had to restart the rails application on the production so I looked for an another answer. I have found it below:
http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger
I just reboot the server with
Ctrl + c
That worked for me

Run Rails commands outside of console

With my large application, the Rails console takes a while to load up. Is there a way to single commands more easily?
I'd also like to be able to automate stuff, and echo "query" | rails console isn't a great way to do things.
Thoughts?
EDIT: What about a long-running process that I can ping queries to whenever I have need?
There are two main ways to run commands outside console:
Rake task which depends on :environment
rails runner (previously script/runner), eg:
$ rails runner "query"
Both are pretty well documented on the rails guide: https://guides.rubyonrails.org/command_line.html#bin-rails-runner
Both of these methods will still take the same time as a console to fire up, but they are useful for non-interactive tasks.
Just pipe it in:
echo 'puts Article.count' | bundle exec rails c
It should now be a lot faster than when then the question was originally asked, because of Spring. It's not immediate, but still a lot faster than spinning up the whole app. Use this for the fast lane, it should run in under a second (assuming your required command is fast):
echo 'puts Article.count' | spring rails c
If you really want a single long-running process, you could easily do it by creating a controller action that simply runs whatever you POST to it, then send commands to it using curl behind an alias. The action would of course be completely insecure and should be triple-guarded against running anywhere near production, but it would be easy to setup.
Solution: bundle exec command allows us to run an executable script in the specific context of the project's bundle - making all gems specified in the Gemfile available to require in Ruby application. In addition it eventually avoids any conflicts with other versions of rake installed globally.
echo '<command>' | bundle exec rails c
for more information look at the documentation of bundler
example:
configuration_item=$(echo 'ConfigurationManager.getKey("authentication_method")' | bundle exec rails c )
echo $configuration_item
#output:
MFA_authentication

Resources