diff --git a/migration/Dockerfile b/migration/Dockerfile index 600115063..25ed414a7 100644 --- a/migration/Dockerfile +++ b/migration/Dockerfile @@ -10,6 +10,7 @@ COPY app.rb . # Install the webrick gem RUN gem install webrick RUN gem install mysql2 +RUN gem install timeout # Expose port 8080 to be accessible from outside the container EXPOSE 8080 diff --git a/migration/README.md b/migration/README.md new file mode 100644 index 000000000..4cd53263d --- /dev/null +++ b/migration/README.md @@ -0,0 +1,10 @@ +Temporary README to explain how to run docker in this subdirectory. + +setup: unzip the db initialization file sql-data/init.sql.gz. + - it is too large for git to handle unless zipped + - make sure not to commit this change when pushing +start: docker-compose up --build -d + - d flag runs detached in background + - build processes any changes in the Dockerfile +stop: docker-compose down -v + - v flag removes volumes which is necessary when starting the next time diff --git a/migration/app.rb b/migration/app.rb index 352896c51..68932dd46 100644 --- a/migration/app.rb +++ b/migration/app.rb @@ -1,12 +1,47 @@ require 'webrick' require 'mysql2' +require 'timeout' + +# Method to check if the database is up and running +def wait_for_db(host:, username:, password:, database:, timeout: 60, interval: 5) + start_time = Time.now + + while Time.now - start_time < timeout + begin + Timeout.timeout(interval) do + client = Mysql2::Client.new( + host: host, + username: username, + password: password, + database: database + ) + client.query('SELECT 1') # Simple query to check connection + client.close + return true + end + rescue Mysql2::Error => e + puts "Database connection failed: #{e.message}. Retrying..." + sleep interval + end + end + + raise "Database did not become available within #{timeout} seconds." +end + +# Wait for the MySQL database to be ready +wait_for_db( + host: 'db', # Docker Compose service name + username: 'root', + password: 'password', + database: 'antcat' +) # Configure the MySQL client client = Mysql2::Client.new( - host: 'db', # Docker Compose service name + host: 'db', username: 'root', password: 'password', - database: 'mydatabase' + database: 'antcat' ) # Define the web server @@ -15,10 +50,10 @@ # Define a response for the root path "/" server.mount_proc '/' do |req, res| # Query the database - results = client.query('SELECT * FROM mytable') + results = client.query('SELECT name FROM names LIMIT 100') # Build the HTML response - html = '